Network Programming
Agenda
What is networking and why? Elements of Client Server Computing Networking Basics Understanding Ports and Sockets Java Sockets
Implementing a Server Implementing a Client
Sample Examples UDP socket communication
2
Introduction to Networking
Networking means connecting many clients to a server for some purpose. Internet and WWW have emerged as global ubiquitous media for communication. Java supports networking. All networking classes are in java.net package.
3
Internet Applications Serving Local and Remote Users
PC client
Internet Server
Local Area Network
PDA
4
Why Networking ?
Businesses are continuously seeking new and innovative ways and means for offering their services via the Internet. To bring whole world close together.
Elements of C-S Computing
a client, a server, and network
Re qu es t
Client
Server
Re su
Network
lt
Client machine
Server machine
6
Client / Server Model Examples
Application Web Browsing Email Streaming Music Client Internet Explorer, Mozilla Firefox MS Outlook, Thunderbird Windows Media Player, iTunes Server Apache POP, IMAP, SMTP Internet Radio Game Servers
7
Online Gaming Half-Life, Everquest, PartyPoker
Networking Basics
Applications Layer
TCP/IP Stack
Standard apps
HTTP FTP Telnet
User apps TCP UDP Programming Interface:
Transport Layer
Application (http,ftp,telnet,) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)
Sockets
Network Layer
IP Device drivers
Link Layer
We are focused on Transport layer only.
8
TCP
TCP (Transport Control Protocol) is a connection-oriented protocol that provides a reliable flow of data between two computers. Example applications:
HTTP FTP Telnet
UDP
UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. Example applications:
Ping
10
Ports
11
Understanding Ports
The TCP and UDP protocols use ports. A 16-bit number that identifies each service offered by a network server. app
port
server
P o r t
TCP
Client
app port
app port
app port Packet port# data 12
TCP or UDP Data
Understanding Ports
Port is represented by a positive (16-bit) integer value ( 0 to 65535). Some ports have been reserved to support common/well known services:
ftp 21/tcp telnet 23/tcp smtp 25/tcp login 513/tcp http 80/tcp POP3 110 Post office protocol
User level process/services generally use port number value >= 1024
13
Networking classes in JDK
java.net.* provides the classes for implementing networking applications.
java.net package can be roughly divided in two sections: A Low Level API which deals with the following abstractions: Addresses, which are networking identifiers, like IP addresses. Sockets, which are basic bidirectional data communication mechanisms. Interfaces, which describe network interfaces. A High Level API which deals with the following abstractions: URLs, which represent Uniform Resource Locators. Connections, which represents connections to the resource pointed to by URLs.
14
IP Address
15
16
17
18
InetAddress Class
Represents an IP address Can convert domain name to IP address
Performs DNS lookup getLocalHost() getByName(String host) getByAddress(byte[] addr)
Getting an InetAddress object
19
Finding IP address
import java.net.*; class ipaddress { public static void main(String ar[])throws Exception{ InetAddress ad=InetAddress.getLocalHost(); System.out.println(ad); InetAddress ad1=InetAddress.getByName("www.google.com"); System.out.println(ad1); InetAddress ad2=InetAddress.getByName("www.yahoo.com"); System.out.println(ad2); } }
20
URL Class
Provides high-level access to network data Abstracts the notion of a connection Constructor opens network connection
To resource named by URL
URL (Uniform Resource Locator) is a reference (an address) to a resource on the Internet.
21
URL Constructors
URL( fullURL ) URL( "http://java.sun.com/topic/index.html" ) URL( baseURL, relativeURL ) URL base = new URL("http://iimb.edu/" ); URL class = new URL( base, "/class/index.html " ); URL( protocol, baseURL, relativeURL ) URL( "http", www.iimb.edu, "/class/index.html" ) URL( protocol, baseURL, port, relativeURL ) URL( "http", www.cs.umd.edu,80,"/class/index.html) );
22
Parsing URL and URL Methods
getProtocol( ) getHost( ) getPort( ) getFile( ) getContent( ) openStream() openConnection()
23
Parsing a URL
The URL class provides several methods that let you query URL objects:
getProtocol() Returns the protocol identifier component of the URL. getHost() Returns the host name component of the URL. getPort() Returns the port number component of the URL. The getPort method returns an integer that is the port no. If the port is not set, getPort returns -1.
24
Parsing a URL
getPath() Returns the path component of this URL. getQuery() Returns the query component of this URL. getFile() Returns the filename component of the URL. The getFile method returns the same as getPath, plus the concatenation of the value of getQuery.
25
Parsing a URL
import java.net.*; import java.io.*; public class ParseURL { public static void main(String[] args) throws Exception { URL aURL = newURL("http://java.sun.com:80/docs/books/tutorial" + "/index.html?name=networking#DOWNLOADING"); System.out.println("protocol = " + aURL.getProtocol()); System.out.println("authority = " + aURL.getAuthority()); System.out.println("host = " + aURL.getHost()); System.out.println("port = " + aURL.getPort()); System.out.println("path = " + aURL.getPath()); System.out.println("query = " + aURL.getQuery()); System.out.println("filename = " + aURL.getFile()); System.out.println("ref = " + aURL.getRef()); } }
26
Output of previous program
protocol = http authority = java.sun.com:80 host = java.sun.com port = 80 path = /docs/books/tutorial/index.html query = name=networking filename =
/docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING
27
Reading contents from Server
28
Reading contents from Server
You can call the URL's openStream() method to get a stream from which you can read the contents of the URL. The openStream() method returns a java.io.InputStreamobject, so reading from a URL is as easy as reading from an input stream. This method is a shorthand for: openConnection().getInputStream()
29
Example
import java.net.*; import java.io.*; public class URLReader { public static void main(String[] args) throws Exception { URL yahoo = new URL("http://localhost:8888/index.jsp");
BufferedReader in = new BufferedReader( new InputStreamReader(yahoo.openStream()));
String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } }
30
URL Connection Classes
High level description of network service Access resource named by URL Can define own protocols Examples
URLConnection Reads resource HttpURLConnection Handles web page
31
32
Socket
33
Socket
Network communication using Sockets is very much similar to performing file I/O. Socket-based communication is programming language independent.
That means, a socket program written in Java language can also communicate to a program written in Java or non-Java socket program. It is called Remote Procedure Call (RPC).
34
Socket Communication
A server (program) runs on a specific computer and has a socket that is bound to a specific port. The server waits and listens to the socket for a client to make a connection request.
server
Connection request Client
port
35
36
Socket Methods
37
38
ServerSocket Methods
39
Programming Socket (TCP-based)..
40
Implementing a Server
1. Open
the Server Socket: ServerSocket server; DataOutputStream os; DataInputStream is; server = new ServerSocket( PORT ); 2. Wait for the Client Request: Socket client = server.accept(); 3. Create I/O streams for communicating to the client is = new DataInputStream( client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() ); 4. Perform communication with client Receive from client: String line = is.readLine(); Send to client: os.writeBytes("Hello\n"); 5. Close sockets: client.close();
41
Implementing a Client
1. Create a Socket Object: client = new Socket( server, port_id ); 2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() );
3. Perform I/O or communication with the server:
Receive data from the server: Send data to the server:
String line = is.readLine();
os.writeBytes("Hello\n"); 4. Close the socket when done: client.close();
42
A simple server (simplified code)
// SimpleServer.java: a simple server program import java.net.*; import java.io.*; public class SimpleServer { public static void main(String args[]) throws IOException { // Register service on port 1234 ServerSocket s = new ServerSocket(1234); Socket s1=s.accept(); // Wait and accept a connection // Get a communication stream associated with the socket OutputStream s1out = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream (s1out); // Send a string! dos.writeUTF("Hi there"); // Close the connection, but not the server socket dos.close(); s1out.close(); s1.close(); } }
43
A simple client (simplified code)
// SimpleClient.java: a simple client program import java.net.*; import java.io.*; public class SimpleClient { public static void main(String args[]) throws IOException { // Open your connection to a server, at port 1234 Socket s1 = new Socket(192.168.1.164",1234); // Get an input file handle from the socket and read the input InputStream s1In = s1.getInputStream(); DataInputStream dis = new DataInputStream(s1In); String st = new String (dis.readUTF()); System.out.println(st); // When done, just close the connection and exit dis.close(); s1In.close(); s1.close(); } }
44
Server in Loop: Always up
// SimpleServerLoop.java: a simple server program that runs forever in a single thead
import java.net.*; import java.io.*; public class SimpleServerLoop { public static void main(String args[]) throws IOException { // Register service on port 1234 ServerSocket s = new ServerSocket(1234); while(true) { Socket s1=s.accept(); // Wait and accept a connection // Get a communication stream associated with the socket OutputStream s1out = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream (s1out); // Send a string! dos.writeUTF("Hi there"); // Close the connection, but not the server socket dos.close(); s1out.close(); s1.close(); } } }
45
Multithreaded Server: For Serving Multiple Clients Concurrently
Client 1 Process
Server Process
Server Threads
Internet
Client 2 Process
46
Multi Threaded Server
class MTServer{ public static void main() { ServerSocket ss=new ServerSocket(1234); Socket cs=ss.accept(); ClientHandler ch=new ClientHandler(cs); }} class ClientHandler extends Thread { Socket cs; public ClientHandler (Socket cs) { this.cs=cs; } public void run() { //code to interact with the current client. } }
47
Programming Communication (UDP-based)..
48
Connection Less communication
Packet oriented communication resolves network traffic issue and hence faster data transmission. No guaranteed delivery. Packets wont reach in sequence. Each packet contains
InetAddress Port of destination Data
49
Packet
Data in packet represented as byte array
50
UDP Server
Creates a DatagramSocket. Blocks until a DatagramPacket from a client is received. On receipt of a DatagramPacket it reads, processes and sends a response DatagramPacket back to the client.
UDP Client
Creates a DatagramSocket Sends a DatagramPacket to the server. Blocks until a response DatagramPacket is received from the Server.
51
DatagramSocket Class
DatagramSocket classs constructor needs to know the port number where the datagram socket is created. DatagramSocket(int port); The send() and receive() methods are used to send and receive datagram packets.
52
DatagramSocket Methods
close() getLocalAddress() getLocalPort() receive(DatagramPacket p) send(DatagramPacket p) setSoTimeout(int t) getSoTimeout()
53
54
55
DatagramPacket Methods
Other methods..
setAddress() setData() setLength() setPort()
56
Example of UDP-based communication
57
UDP Sender
String str="Hello, this is test"; byte buffer[]=str.getBytes(); int len=buffer.length; InetAddress addr; addr=InetAddress.getByName("localhost"); DatagramPacket packet; packet=new DatagramPacket(buffer, len, addr, 1234); DatagramSocket soc=new DatagramSocket(); soc.send(packet);
58
UDP Receiver
byte buffer[]=new byte[8292]; int len=buffer.length; DatagramPacket packet; packet=new DatagramPacket(buffer,len); DatagramSocket soc=new DatagramSocket(1234); soc.receive(packet); int actuallength=packet.getLength(); String str=new String(buffer,0,actuallength); System.out.println(str);
59
60