Java Networking (sockets) Rui Moreira Links: http://java.sun.com/docs/books/tutorial/networking/toc.html#sockets http://www.javaworld.com/javaworld/jw-12-1996/jw-12-sockets_p.html Networking Computers on the Internet communicate via: n Transmission Control Protocol (TCP) connection-oriented protocol (like a telephone call synchronous communication) that provides a reliable flow of data between 2 computers (the order of packets is guaranteed) n User Datagram Protocol (UDP) connectionless protocol (like a mail letter asynchronous communication) that uses independent packets of data (datagrams) with no guarantees about arrival Rui Moreira 2 1
Networking (java.net package) Java programmers work at Application level, i.e., do not need to concern about the TCP/UDP layers because the java.net package : n hides the network details n provides system-independent communication Rui Moreira 3 Socket (IP + Port #) Sockets are uniquely identified on the entire Internet with 2 numbers: n Internet Address (IP address): 32-bit integer that uniquely identifies one machine (host / node) IPv6 increases the size of the IP address to 128 bits n Port of the socket: 16-bit integer called the port number (0-65553); In practice Java represents ports with 32-bit integers; Port numbers below 1024 are reserved for predefined services (e.g. telnet, SMTP, FTP) Rui Moreira 4 2
InetAddress The InetAddress class encapsulates the concept of an IP address and has methods for: n byte[] getaddress(): Returns the raw IP address of this InetAddress object; n String gethostaddress() Returns the IP address string in textual presentation; n String gethostname() Gets the host name for this IP address; n static InetAddress getlocalhost() Returns the local host; Rui Moreira 5 Sockets Server App ServerSocket (port #) Client App Socket (host, port #) port # Packet data TCP / UDP 1. Server registers Socket on a given port number (port #) 2. Gets the OutputStream associated with the socket 3. Writes the data 1. Client opens connection to given host & port # 2. Gets the InputStream associated with the socket 3. Reads the data Rui Moreira 6 3
Minimal TCP/IP Server import java.net.*; import java.io.*; public class SimpleServer { public static void main(string[] args){ ServerSocket serv = null; Socket sock = null; String srt = Hello net world! ; OutputStream os = null; DataOutputStream dos = null; // Register service on port 5432 serv = new ServerSocket(5432); catch (IOException ioe) { // Run listen/accept loop while (true) { // Wait for connection and then get stream sock = serv.accept(); os = sock.getoutputstream(); dos = new DataOutputStream(os); // Send string in UTF (machine independent) format dos.writeutf(str); dos.close(); os.close(); sock.close(); catch (IOException ioe) { Rui Moreira 7 Minimal TCP/IP Client import java.net.*; import java.io.*; public class SimpleClient { public static void main(string[] args){ String localhost_ip =(InetAddress.getLocalHost()).getHostAddress(); Socket sock = null; InputStream is = null; DataInputStream dis = null; // Open connection to localhost on port 5432 sock = new Socket(localhost_ip, 5432); // Get Input Stream is = sock.getinputstream(); dis = new DataInputStream(is); // Read string String str = new String(dis.readUTF()); System.out.println( SimpleClient main(): str = +str); // Close streams and connection dis.close(); is.close(); sock.close(); catch (IOException ioe) { Rui Moreira 8 4
Minimal UDP Server public class QuoteServer { public static void main(string[] args){ DatagramSocket socket = null; BufferedReader in = null; boolean morequotes = true; socket = new DatagramSocket(4445); in = new BufferedReader(new FileReader("one-liners.txt")); catch () { while (morequotes) { byte[] buf = new byte[256]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // figure out response String dstring = null; if (in == null) dstring = new Date().toString(); else dstring = getnextquote(); buf = dstring.getbytes(); // send response to client at "address" and "port" InetAddress address = packet.getaddress(); int port = packet.getport(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); catch (IOException e) { morequotes = false; socket.close(); protected String getnextquote() { /* Next slide */ Rui Moreira 9 Minimal UDP Server (cont.) public class QuoteServer { protected String getnextquote() { String returnvalue = null; if ((returnvalue = in.readline()) == null) { in.close(); morequotes = false; returnvalue = "No more quotes. Goodbye."; catch (IOException e) { returnvalue = "IOException occurred in server."; return returnvalue; Rui Moreira 10 5
Minimal UDP Client import java.net.*; import java.io.*; import java.util.*; public class QuoteClient { public static void main(string[] args) throws java.io.exception { if (args.length!= 1) { System.out.println("Usage: java QuoteClient <hostname>"); return; // get a datagram socket DatagramSocket socket = new DatagramSocket(); // send request byte[] buf = new byte[256]; InetAddress address = InetAddress.getByName(args[0]); DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445); socket.send(packet); // get response packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // display response String received = new String(packet.getData()); System.out.println("Quote of the Moment: " + received); socket.close(); Rui Moreira 11 6