1 / 44

Network Programming

Network Programming. Terms. Network Programming involves writing programs that communicate with other programs across a computer network. A server is an application that provides a "service" to various clients who request the service

cargan
Download Presentation

Network Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Network Programming

  2. Terms • Network Programming involves writing programs that communicate with other programs across a computer network. • A server is an application that provides a "service" to various clients who request the service • In general, Peer-to-Peer computing is done. Many strategies are available

  3. Java technology allows: • internet clients to connect to servlets or back-end business systems (or databases). • applications to connect to one another using sockets. • applications to connect to one another using RMI (remote method invocation). • some others • A Protocol is a standard pattern of exchanging information

  4. Network Programming • As far as a program is concerned, a network is just another possible source of input data, (online) and another place where data can be output. That does oversimplify things, because networks are not as easy to work with as files are. • But in Java, you can do network communication using input streams and output streams, just as you can use such streams to communicate with the user or to work with files. Nevertheless, opening a network connection between two computers is a bit tricky, since there are two computers involved and they have to somehow agree to open a connection. And when each computer can send data to the other, synchronizing communication can be a problem. But the fundamentals are the same as for other forms of I/O.

  5. Network Basics • Network Programming involves writing programs that communicate with other programs across a computer network. • There are many different strategies for allowing communication between applications. JAVA technology allows: • internet clients to connect to servlets or back-end business systems (or databases). • applications to connect to one another using sockets. • applications to connect to one another using RMI (remote method invocation). • some others

  6. Computers running on the internet typically use one of the following high-level Application Layer protocols to allow applications to communicate: • Hyper Text Transfer Protocol (HTTP) • File Transfer Protocol (FTP) • Telnet • In a lower Transport Layer of communication, there is a separate protocol which is used to determine how the data is to be transported from one machine to another: • Transport Control Protocol (TCP) • User Datagram Protocol (UDP) • Beneath that layer is a Network Layer for determining how to locate destinations for the data (i.e., address). And at the lowest level (for computers) there is a Link Layer which actually handles the transferring of bits/bytes.

  7. TCP • TCP is a reliable, in-order transport protocol. Every package send by the source is guaranteed to arrive at its destination in the same order as it was sent. The limitation for TCP/IP is there can only be one sender and one receiver. Multicasting is not supported. • UDP • UDP does not guarantee the order of package delivery, it does not even guarantee that a package will be delivered to its destination. UDP is simpler than TCP, with less overhead (shorter header and no package sequence number, no re-transmission). It is often used for delivering video/voice over a IP network (VoIP). UDP supports multicast, where one package can be received by everyone joining the multicast group (within the time-to-live number of hops from the sender). • Socket (or Port) • Socket is a end-point for networking communication. TCP and UDP supports 64K sockets, from socket number 0 to socket number 65,535. Socket number between 0 to 1023 are reserved for popular application protocols (e.g., Port 80 for HTTP, Port 443 for HTTPS, Port 21 for FTP, Port 23 for Telnet, Port 25 for SMTP, Port 110 for POP3, etc. Port number on and above 1024 are available for your testing.

  8. A Protocol is a standard pattern of exchanging information. • A port is used as a gateway or "entry point" into an application. • A computer's address is a 32-bit IP address. The port number is a 16-bit number ranging from 0 to 65,535, with ports 0-1023 restricted by well-known applications like HTTP and FTP.

  9. Client/Server Communications • A server is any application that provides a service and allows clients to communicate with it. • A client is any application that requests a service from a server. • Using TCP the client and server must establish a connection in order to communicate. To do this, each program binds a socket to its end of the connection.

  10. Using TCP the client and server must establish a connection in order to communicate. To do this, each program binds a socket to its end of the connection.

  11. C/S Program TCP pgm • A program, called the server blocks waiting for a client to connect to it • A client connects • The server and the client exchange information until they're done • The client and the server both close their connection

  12. Server.java import java.io.*; import java.net.*; class server { public static void main(String args[]) throws IOException{ try { System.out.println("Entered"); ServerSocketss = new ServerSocket(3000); System.out.println(ss); Socket s=ss.accept(); BufferedReader b=new BufferedReader(new InputStreamReader(s.getInputStream())); String str=b.readLine(); System.out.println("From Client: " +str); ss.close(); s.close(); } catch(Exception e) { System.out.println(e); } } }

  13. Client.java import java.net.*; import java.io.*; class client { public static void main(String args[])throws IOException { try { Socket s=new Socket("LocalHost",3000); BufferedReader b=new BufferedReader(new InputStreamReader(System.in)); String str=b.readLine(); PrintWriter pw=new PrintWriter(s.getOutputStream(),true); pw.println(str); s.close(); } catch(IOException e) { System.out.println("Error..."+e); } } }

  14. UDP & Datagrams Sockets • In the datagram protocol (i.e., UDP) there is no direct socket connection between the client and the server. That is, packets are received "in seemingly random order" from different clients. • It is similar to the way email works. If the client requests or server responses are too big, they are broken up into multiple packets and sent one packet at a time.

  15. C/S Program • Uses DatagramSockets and DatagramPackets. • The server will be in a infinite loop accepting messages, although there will be no direct socket connection to the client. • We will be setting up a buffer (i.e., an array of bytes) which will be used to receive incoming requests. Each message is sent as a packet. Each packet contains: • the data of message (i.e., the message itself) • the length of the message (i.e., the number of bytes) • the address of the sender (as an InetAddress) • the port of the sender

  16. The code for packaging and sending an outgoing packet involves creating a DatagramSocketand then constructing a DatagramPacket. • The packet requires an array of bytes, as well as the address and port in which to send to. The byte array can be obtained from most objects by sending a getBytes() message to the object. Finally, a send() message is used to send the packet. • The InetAddressclass provides methods to get the IP of any host name.

  17. DatagramSocket & DatagramPacket • The DatagramSocket class represents a connection-less socket for sending and receiving datagram packets. • The DatagramPacket is message that can be sent or received. If you send multiple packet, it may arrive in any order. Moreover, packet delivery is not guaranteed. • DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to receive the packets. • DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet. This constructor is used to send the packets.

  18. Sender import java.net.*;   publicclassDSender{   publicstaticvoid main(String[] args) throws Exception {   DatagramSocketds = newDatagramSocket();       String str = "Welcome java";   InetAddressip = InetAddress.getByName("127.0.0.1");   DatagramPacketdp = newDatagramPacket(str.getBytes(), str.length(), ip, 3000);   ds.send(dp);   ds.close();     }   }  

  19. Receiver import java.net.*;   publicclassDReceiver{   publicstaticvoid main(String[] args) throws Exception {   DatagramSocketds = newDatagramSocket(3000);   byte[] buf = newbyte[1024];   DatagramPacketdp = newDatagramPacket(buf, 1024); ds.receive(dp);       String str = newString(dp.getData(),0, dp.getLength()); System.out.println(str);   ds.close();     }   }  

  20. RMIRemote Method Invocation

  21. RMI • The Remote Method Invocation (RMI) is an API that provides a mechanism to create distributed application in java. The RMI allows an object to invoke methods on an object running in another JVM. • The RMI provides remote communication between the applications using two objects stub and skeleton.

  22. Stub & Skeleton RMI uses stub and skeleton object for communication with the remote object. A remote object is an object whose method can be invoked from another JVM. Let's understand the stub and skeleton objects: stub • The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through it. It resides at the client side and represents the remote object. When the caller invokes method on the stub object, it does the following tasks: • It initiates a connection with remote Virtual Machine (JVM), • It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM), • It waits for the result • It reads (unmarshals) the return value or exception, and • It finally, returns the value to the caller. skeleton • The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are routed through it. When the skeleton receives the incoming request, it does the following tasks: • It reads the parameter for the remote method • It invokes the method on the actual remote object, and • It writes and transmits (marshals) the result to the caller.

  23. Stub & Skeleton

  24. Creating Distributed Applications Using RMI • Steps to create a RMI application: • Design and implement the components of your distributed application. • Compile sources and generate stubs. • Make classes network accessible. • Start the application.

  25. The server class • The class that defines the server object should extend UnicastRemoteObject • This makes a connection with exactly one other computer • If you must extend some other class, you can use exportObject() instead • Sun does not provide a MulticastRemoteObject class • The server class needs to register its server object: • String url = "rmi://" + host + ":" +port + "/" + objectName; • The default port is 1099 • Naming.rebind(url, object); • Every remotely available method must throw a RemoteException (because connections can fail) • Every remotely available method should be synchronized

  26. Step I: 1: creates remote interface import java.rmi.*; public interface AddServerIntf extends Remote{ double add(double d1,double d2) throws RemoteException; }

  27. Step 2: implements remote interface import java.rmi.*; import java.rmi.server.*; public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf{ public AddServerImpl() throws RemoteException{} public double add(double d1,double d2) throws RemoteException{ return d1+d2; } }

  28. Step 3:Server main program import java.rmi.*; import java.rmi.server.*; public class AddServer{ public static void main(String args[]){ try{ AddServerImpladdServerImpl = new AddServerImpl(); Naming.rebind(“AddServer”,addServerImpl); } Catch(Exception e) {System.out.println(“Exception :”+e); }}}

  29. Step 4:Client main program import java.rmi.*; public class AddClient{ public static void main(String args[]){ try{ String addServerURL=“rmi://”+args[0]+”/AddServer”; AddServerIntfaddServerIntf=(AddServerIntf)Naming.lookup(addServerURL); System.out.println(“The 1 no is:+args[1]);

  30. pgm cont… Double d1=Double.valueOf(args[1]).doubleValue(); System.out.println(“2nd no is:”+args[2]); double d2=Double.valueOf(args[2]).doubleValue(); System.out.println(“sum is: ”+addServerIntf.add(d1,d2)); } catch(Exception e) { System.out.println(“Exception “+e);}}}

  31. Step II:create the stub and skeleton objects using the rmic tool. • Next step is to create stub and skeleton objects using the RMI compiler. The rmic tool invokes the RMI compiler and creates stub and skeleton objects. rmicAddServerImpl • This command generates 2 new files: AddServerImpl_Skel.class & AddServerImpl_Stub.class

  32. Step III: Install files • Copy AddClient.class, AddServerImpl_Stub.class, AddServerIntf.class to the client machine • Copy AddServerIntf.class , AddServerImpl.class, AddServerImpl_Skel.class, AddServer.class, AddServerImpl_Stub.class to the server machine

  33. Step IV: Start RMI registry • Rmiregistry executes on the server machine. • It maps names to object references • Check CLASSPATH and start the rmiregistry by typing in the command line start rmiregistry • A new window is opened and keep this window opened until you finish the whole RMI program execution

  34. Step V: Start the server • run the server java AddServer • The AddServer code initiates AddServerImpland registers that object with the name “AddServer”

  35. Step VI:Start the Client • run the client program java AddClientxyz 20 10 or java AddClient127.0.0.1 20 10

  36. Another Pgm

  37. Hello world server: interface • import java.rmi.*;public interface HelloInterface extends Remote { public String say() throws RemoteException;}

  38. Hello world server: class • import java.rmi.*;import java.rmi.server.*;public class Hello extends UnicastRemoteObject implements HelloInterface { private String message; // Strings are serializable public Hello (String msg) throws RemoteException { message = msg; } public String say() throws RemoteException { return message; }}

  39. Registering the hello world server • class HelloServer { public static void main (String[] argv) { try { Naming.rebind("rmi://localhost/HelloServer", new Hello("Hello, world!")); System.out.println("Hello Server is ready."); } catch (Exception e) { System.out.println("Hello Server failed: " + e); } }}

  40. The hello world client program • class HelloClient { public static void main (String[] args) { HelloInterface hello; String name = "rmi://localhost/HelloServer"; try { hello = (HelloInterface)Naming.lookup(name); System.out.println(hello.say()); } catch (Exception e) { System.out.println("HelloClient exception: " + e); } }}

  41. rmic • The class that implements the remote object should be compiled as usual • Then, it should be compiled with rmic: • rmic Hello • This will generate files Hello_Stub.class and Hello_Skel.class • These classes do the actual communication • The “Stub” class must be copied to the client area • The “Skel” was needed in SDK 1.1 but is no longer necessary

  42. Trying RMI • In three different terminal windows: • Run the registry program: • rmiregistry • Run the server program: • java HelloServer • Run the client program: • java HelloClient • If all goes well, you should get the “Hello, World!” message

  43. Mod IV Ends

More Related