Java networking Carlo U. Nicola, IMVS With extracts from slides/publications of : Dominik Gruntz, IMVS and from the book of K.J. Calvert and M.J. Donahoo TCP in Java
Topics 1. Network & IP 2. TCP Sockets 3. UDP Sockets CDA FS13 2
Static factory methods Name or IP Address (as String) Instance methods fully qualified host name ICMP Echo Request / Echo CDA FS13 3
Network Interfaces Network Interfaces and its addresses: CDA FS13 4
Sockets Socket Abstraction through which an application may send and receive data through the network A Socket is identified by Hostname/IP and port number Connection Types Stream Sockets Use TCP as end-to-end protocol Provide a reliable byte-stream Connection oriented: Socket represents one end of a TCP connection Datagram Sockets Use UDP as protocol Not connection oriented, not reliable CDA FS13 5
TCP Socket Stream Socket Permanent & reliable connection between a machine A and a machine B Packages are delivered in correct order Lost packages are retransmitted Connection to a server is full-duplex The programs can talk to each other The Socket establishes an input- and output stream After transmission one or both sides close the connection Lowest-level form of communication from application developer s view Programmer is responsible for managing the flow of bytes between machines Higher-level techniques: Message passing systems (SOAP, JMS) Extensions to Web Servers (Servlets, JSP, ASP, ) Distributed Objects (RMI) CDA FS13 6
TCP Socket: Socket constructors: // creates unconnected Socket // creates unconnected Socket with a proxy [Java 1.5] // unconnected Sockets! bind method CDA FS13 7
TCP Socket: Socket Methods / / // disables output stream // closes input stream CDA FS13 8
Simple Client (Echo) CDA FS13 10
Sample Client (Mailer) CDA FS13 11
Sample Client (Mailer) CDA FS13 12
Runs on a server and listens for incoming calls Bound to an IP Address and a port Only one process may listen on one port Backlog The OS stores incoming connections not yet accepted in a FIFO queue The default length of this queue is 50 in Java, but cannot exceed OS limits (Solaris = 5) CDA FS13 13
Server Socket: opens a listener on a specific port, 0 for a system allocated port number multihomed server, only accepts request on bindaddr Connections: blocks until a connection is requested timeout for accept ServerSocket server = new ServerSocket( port ); server.setsotimeout( 60000 ); // Timeout after 1 min try { Socket socket = server.accept(); } catch ( InterruptedIOException e ) { System.err.println( "Timeout after one minute" ); } CDA FS13 14
Echo Server CDA FS13 15
Concurrent Echo Server Problem: Server can serve at most one client Solutions: Thread-per-client After accept returns a socket, start a new thread which answers this request and immediately call accept again Thread-pool Start n threads where each handles client by client Multiple threads may call accept simultaneously on the same server socket. Upon a connection request, one thread is selected. Thread-pool from NIO Executors / ExecutorService CDA FS13 16
(threaded) CDA FS13 17
(threaded) CDA FS13 18
(threaded) CDA FS13 19
(threaded) CDA FS13 20
UDP UDP User Datagram Protocol UDP also uses Ports Server may listen on a port for both TCP and UDP packets UDP Features UDP adds another layer of addressing (ports) to that of IP UDP extends IP so that it works between applications (not only hosts) UDP detects some form of data corruption that may occur in transit and discards corrupted messages UDP retains message boundaries CDA FS13 23
UDP Connection-Less No initial connection handshake Every package is delivered individually UDP packets may be lost Multiple packets sent from one machine to another may be routed differently and thus may arrive in any order But: every correctly received package is complete (check-sum) UDP is faster than TCP, but not reliable Applications must deal with losses, reorderings, CDA FS13 24
DatagramSockets DatagramSocket Is bound to a port Is used as sender and as receiver of datagram packets When used as receiver then usually a port is specified Constructors binds socket to any available port binds socket to given port binds socket to a local address. If local address is not specified, then the socket can receive packets on any of the local addresses. CDA FS13 25
DatagramSockets Connecting and Closing Connected means, that the communication is restricted to a particular host and port, i.e. packages can be sent only / received only from a particular host/port restricts sending/receiving of packets to a host/port breaks restriction returns restriction host (or null) returns restriction port (or -1) returns whether restriction is active indicates that socket is no longer in use Addressing returns the address to which socket is bound returns the port on which the socket is bound CDA FS13 26
DatagramSockets Sending/Receiving Send sends a data packet to the connection address (if packet does not specify an address, otherwise it must be the same) Send does NOT block Receive blocks until a datagram is received sends a datagram packet waits for an incoming datagram packet Options Timeout for receive the Enable/disable with specified timeout, in milliseconds. Retrive setting for CDA FS13 27
DatagramPacket DatagramPacket Packages delivered, contains address of receiver or sender creates packet (for receiving messages of a given length) length buf.length Creates a datagram packet for sending packets of a given length on the specified host / / / CDA FS13 28
UDPServer public class UDPServer { public static void main(string args[]) throws Exception { DatagramSocket socket = new DatagramSocket(4711); DatagramPacket packet = new DatagramPacket(new byte[1024], 1024); while (true) { socket.receive(packet); InetAddress address = packet.getaddress(); int port = packet.getport(); int len = packet.getlength(); byte data[] = packet.getdata(); } } } System.out.println("Request from " + address + " from port " + port + " of length " + len + "\n" + new String(data, 0, len)); CDA FS13 29
UDPClient class UDPClient { public static void main(string args[]) throws Exception { DatagramPacket packet; while (true) { InetAddress ia = InetAddress.getByName("localhost"); String s = new Date().toString(); packet = new DatagramPacket( s.getbytes(), s.length(), ia, 4711); DatagramSocket s = new DatagramSocket(); s.send(packet); } } } System.out.println("Weg is es"); Thread.sleep(1000); CDA FS13 30
UDP Implementation Server Single socket for all incoming datagrams Address / returns source address upon receipt / returns destination address upon sending Buffer Size Server accepts in example code datagrams with max size 1024 bytes Any excess is silently discarded by the socket Send No associated queue (since no guarantees about transmission) CDA FS13 31
UDP Comments Reuse of DatagramPackets Datagram package may be used for several receive calls Length field is set when a message is received Has to be reset to the actual length of the datagram before subsequent call to receive CDA FS13 32
UDP Comments Reuse of DatagramPackets Datagram package may be used for several receive calls Length field is set when a message is received Has to be reset to the actual length of the datagram before subsequent call to receive CDA FS13 33