Network Communication
Outline Sockets Datagrams TCP/IP Client-Server model
OSI Model
Sockets Endpoint for bidirectional communication between two machines. To connect with each other, each of the client and the server binds a socket to its end for reading and writing: read from socket input and write to socket output Characterized by: Local address: IP: identifies computer Port number: identifies application Protocol: ex: TCP, UDP
Socket types Datagram sockets connectionless sockets use User Datagram Protocol (UDP). Stream sockets connection-oriented sockets use Transmission Control Protocol (TCP) Raw sockets available in routers
Datagrams The UDP protocol provides a mode of network communication whereby datagrams are sent over the network. java.net.datagramsocket used for the connection. A datagram s arrival, arrival time and order of arrival is not guaranteed.
Communicating through datagrams Create a socket on local machine to send/receive datagrams: DatagramSocket To send a message: build a packet containing the data: DatagramPacket add the destination IP address: InetAdress send it using DatagramSocket To receive a message: build a packet with an empty buffer wait to receive a message using DatagramSocket
import java.net.*; UDP Example class GetDate { final static int PORT_DAYTIME = 13; public static void main(string[] args) throws Exception { DatagramSocket dgsocket = new DatagramSocket(); InetAddress destination = InetAddress.getByName( server.com");; DatagramPacket datagram; byte[] msg = new byte[256]; datagram = new DatagramPacket(msg, msg.length, destination, PORT_DAYTIME); dgsocket.send(datagram); datagram = new DatagramPacket(msg, msg.length); dgsocket.receive(datagram); String received = new String(datagram.getData()); System.out.println("Time of machine:" + received); dgsocket.close();
TCP / IP Internet Protocol (IP) Rules for moving bits from A to B. Divide data into packets (header bits to say where to go, data bits) and transmit each individually, possibly along different paths. No guarantee packets arrive in order, or even arrive. Transmission Control Protocol (TCP) Rules to provide reliable communication between two computers. Packets arrive, and they arrive in order. resend over IP until recipient acknowledges
Protocols Many higher layer application protocols use TCP/IP. Used by http, smtp, telnet, ftp. Ex: HyperText Transfer Protocol (HTTP). Set of rules for transferring files (text, graphics, video). Web-server waits for connection requests. Browser establishes connection with Web-server Browser issues GET and POST commands. Web-server responds with header and body.
Client-server model Client: creates socket to communicate with specified server. Socket Server: creates one socket to listen for connection requests creates other sockets to communicate with each client. ServerSocket
Establish a simple server 1. Create a ServerSocket object: ServerSocket server = new ServerSocket(port, queuelength); 2. The server listens indefinitely (or blocks) for an attempt by a client to connect: Socket connection = server.accept(); 3. Get the OutputStream and InputStream objects that enable the server to communicate with the client by sending and receiving bytes: InputStream input = connection.getinputstream(); OutputStream output = connection.getoutputstream(); 4. Processing phase: the server and the client communicate via the InputStream and the OutputStream objects 5. After the communication completes, the server closes the connection by invoking close() on the Socket and the corresponding streams
Establish a simple client 1. Create a Socket object: Socket connection = new Socket (serveraddress, port); 2. Get the OutputStream and InputStream of the Socket. The server and the client must send and receive the data in the same format 3. Processing phase: the server and the client communicate via the InputStream and the OutputStream objects 4. After the communication completes, the client closes the connection.
Multi-threaded server Server listens for connection requests in one thread. Server handles communication with each client in a separate thread. Makes server scalable can accept requests, independent of speed in handling them.
Server example class Serveur { public static void main(string[] arg) { int portecoute = 10302; ServerSocket standardiste; Socket socket; try { standardiste = new ServerSocket(portEcoute); while(true) { socket = standardiste.accept(); new Service(socket); catch(ioexception exc) { System.out.println("probleme de connexion");
Server example class Service extends Thread { Socket socket; BufferedReader entree; PrintStream sortie; Service(Socket socket) { this.socket = socket; try { entree = new BufferedReader(new InputStreamReader(socket.getInputStream())); sortie = new PrintStream(socket.getOutputStream()); this.start(); catch(ioexception exc) { try { socket.close(); catch(ioexception e){ public void run() { String texte; try { while(!(texte = entree.readline()).equals("end")) //do some processing with texte sortie.println( reply to client"); sortie.close(); entree.close(); socket.close(); catch(ioexception e) {
Client example class Client { public static void main(string[] arg) { int portecouteserveur = 10302; BufferedReader lecteurfichier; BufferedReader entree; PrintStream sortie; String ligne; Socket socket; try { socket = new Socket(arg[1], portecouteserveur); lecteurfichier = new BufferedReader(new FileReader(arg[0])); entree = new BufferedReader(new InputStreamReader(socket.getInputStream())); sortie = new PrintStream(socket.getOutputStream()); while ((ligne = lecteurfichier.readline())!= null) sortie.println(ligne); sortie.println("end"); System.out.println(entree.readLine()); sortie.close(); entree.close();socket.close(); catch(filenotfoundexception exc){system.out.println( Fich.introuvable"); catch(unknownhostexception exc){system.out.println( Dest.inconnu"); catch(ioexception exc){system.out.println("probleme d'entree-sortie");
Other types of communication Peer-to-peer Multicast RMI
Remote Method Invocation RMI allows an object running in one Java Virtual Machine (VM) to invoke methods on an object running in another Java VM Application RMI java.net RMI defines a high-level protocol and API TCP/IP stack network
Distributed objects Simple idea objects existing on one machine (server) may be accessed from another machine through regular method call Eliminates need to marshal and unmarshal data sent over sockets Underlying socket code still exists, but is not programmed by user
Distributed objects Client Host Java Virtual Machine Server Host Java Virtual Machine Client Object Remote Object Stub Skeleton
Remote interface Remote Interface implements implements Client Stub Skeleton Remote Object (Server)
Additional readings Custom networking http://docs.oracle.com/javase/tutorial/ networking/index.html JavaTM Programming Language Basics, Socket Communications http://www.oracle.com/technetwork/java/ socket-140484.htmlsocket.html
Appendix
RMI steps Four files need to be created: An interface listing the methods in the implementation class which you want to make remote (FooInterface.java) The implementation class (Foo.java) A server class, which creates one or more implementation objects and posts them to the registry (FooServer.java) A client that invokes the remote object methods (FooClient.java)
The remote object Interface file (e.g. FooInterface.java) must extend java.rmi.remote All methods in interface must throw java.rmi.remoteexception Implementation file (e.g Foo.java) must extend java.rmi.server.unicastremoteobject and implement FooInterface Explicitly include a call to super() as first line in constructor
The server Server class (e.g. FooServer.java) Create a new object instance Call java.rmi.naming.bind( ) to register the object with the naming service contains String name associated with bound object
The client Calls Naming.lookup() to get remote object reference: uses cast to interface type Handles the RMI exceptions Once the remote object reference obtained, handled as regular object
HelloInterface.java import java.rmi.*; public interface HelloInterface extends Remote { public String say(string msg) throws RemoteException;
Hello.java import java.rmi.*; import java.rmi.server.*; public class Hello extends UnicastRemoteObject implements HelloInterface { private String message; public Hello(String msg) throws RemoteException { message = msg; public String say(string m) throws RemoteException { // return input message - reversing input and suffixing // our standard message return new StringBuffer(m).reverse().toString() + "\n" + message;
HelloServer.java import java.rmi.*; import java.rmi.server.*; public class HelloServer { public static void main(string args[]) { // Create and install a security manager if (System.getSecurityManager() == null) System.setSecurityManager(new RMISecurityManager()); try { Naming.rebind("Hello", new Hello("Hello, world!")); System.out.println("server is running..."); catch (Exception e) { System.out.println("Hello server failed:" + e.getmessage());
HelloClient.java import java.rmi.*; public class HelloClient { public static void main(string args[]) { String path = //server.com/hello"; try { if (args.length < 1) System.out.println( usage: HelloClient <host:port> <string>..."); else path = "//" + args[0] + "/Hello"; HelloInterface hello = (HelloInterface) Naming.lookup(path); for (int i = 0; i < args.length; ++i) System.out.println(hello.say(args[i])); catch(exception e) { System.out.println("HelloClient exception: " + e);
Deploying the application Write and compile the 4 Java files Generate Stub and Skeleton class files from the implementation classes: rmic Hello Start the rmi registry (at server): rmiregistry Start the server with or without the security policy: java -D java.security.policy=policy HelloServer Run the client: java HelloClient testing
Deploying the application Java Virtual Machine Client 2 3 Stub 4 Java Virtual Machine 5 Skeleton Remote Object Server 1 Client obtains a remote reference from the registry, and a stub is created Registry Bob Java Virtual Machine 1 Server creates and registers remote object