Prepared By Prof. Tarannum Bloch Assistant Professor, IT Dept. Past History Java Networking Java Networking is a concept of connecting two or more computing devices together so that we can share resources. Java socket programming provides facility to share data between different computing devices. Advantage of Java Networking ✓ sharing resources ✓ centralize software management Java Networking Past History Terminology The widely used java networking terminologies are given below: ✓ ✓ ✓ ✓ ✓ ✓ IP Address Protocol Port Number MAC Address Connection-oriented and connection-less protocol Socket Networking Terminology Past History 1) IP Address IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets that range from 0 to 255. It is a logical address that can be changed. 2) Protocol A protocol is a set of rules basically that is followed for communication. For example: TCP FTP Telnet SMTP POP etc. 3) Port Number The port number is used to uniquely identify different applications. It acts as a communication endpoint between applications. The port number is associated with the IP address for communication between two applications. Past History Networking Terminology 4) MAC Address MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface Controller). A network node can have multiple NIC but each with unique MAC. 5) Connection-oriented and connection-less protocol In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but slow. The example of connection-oriented protocol is TCP. But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast. The example of connection-less protocol is UDP. 6) Socket A socket is an endpoint between two way communication. Past History Stream What is Stream ? A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. InputStream and OutputStream are the basic stream classes in Java. Client Server Communication Client Server Communication Past History UTF What is UTF ? Unicode is an international standard of character encoding which has the capability of representing a majority of written languages all over the globe. Unicode uses hexadecimal to represent a character. Unicode is a 16-bit character encoding system. The lowest value is \u0000 and the highest value is \uFFFF. Past History writeUTF The java.io.DataOuputStream is having writeUTF(String str) method writes a string to the underlying output stream using modified UTF-8 encoding. Following is the declaration for java.io.DataOutputStream.writeUTF(String str) method − public final void writeUTF(String str) readUTF The java.io.DataInputStream.readUTF() method reads in a string that has been encoded using a modified UTF-8 format. The string of character is decoded from the UTF and returned as String. Declaration Following is the declaration for java.io.DataInputStream.readUTF() method − public final String readUTF() What we need for Java network application programming 1. 2. 3. 4. 5. Server Class ( port number , to accept the connection) Client Class ( IP, Port number ) Input Stream method to read Output Stream method to write Application Login ( what application will do ?) Past History Java Socket Programming Java Socket programming is used for communication between the applications running on different JRE. Java Socket programming can be connection-oriented or connection-less. Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket and DatagramPacket classes are used for connection-less socket programming. The client in socket programming must know two information: 1. 2. IP Address of Server, and Port number. Past Socket Historyclass A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket. Important methods Past History Class ServerSocket The ServerSocket class can be used to create a server socket. This object is used to establish communication with the clients. Important methods Method Description 1) public Socket accept() returns the socket and establish a connection between server and client. 2) public synchronized void close() closes the server socket. Check Programs : Unit2 -> Echo Server and Add Connection Past HistoryOriented Application Examples Do it By Yourself → Currency Converter Check Program → Simple chat Java Datagram Java DatagramSocket and DatagramPacket Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming. Java DatagramSocket class Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets. A datagram is basically an information but there is no guarantee of its content, arrival or arrival time. Commonly used Constructors of DatagramSocket class DatagramSocket() throws SocketException: it creates a datagram socket and binds it with the available Port Number on the localhost machine. DatagramSocket(int port) throws SocketException: it creates a datagram socket and binds it with the given Port Number. DatagramSocket(int port, InetAddress address) throws SocketException: it creates a datagram socket and binds it with the specified port number and host address. Java DatagramPacket class Java DatagramPacket is a message that can be sent or received. If you send multiple packet, it may arrive in any order. Additionally, packet delivery is not guaranteed. Commonly used Constructors of DatagramPacket class 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. Check Program: Datagram Do it By Yourself → Digit Character Count in received String URL (Uniform Resource Locator) • It represents the address that is specified to access some Initially two tier architecture (client server applications) information or resource on internet. Around since the mid-80s. • An example of URL is http://www.sciencedirect.com:80/index.html Client power. (VB, Developer/2000, • RAD Thedevelopment URL contains 4 parts whichPowerBuilder). are as follows :- 1)The to usefor(http://) Client protocol is responsible data access applying business logic and presentation of data 2)The Server name or IP address Only service provided by Server was that of database server. 3)Port number which is optional (by default :80) 4)The file(resource) that is referred. URL Class • Initially It will create URL object in java application. two tier architecture (client server applications) mid-80s. •Around It hassince thethefollowing constructors :- Client power. ✓ URL(String urlSpecifier) development (VB, Developer/2000, PowerBuilder). ✓RADURL(String protocol, String hostName, int port, String path); Client is responsible for data access applying business logic and ✓presentation URL (String of dataprotocol, String hostName, String path); ✓ URL (URL urlObj, String urlSpecifier); Only service provided by Server was that of database server. URL Class (cont…) ItInitially contains following instance methods two tier architecture (client server applications) Around Method since the mid-80s. Method Description public String getProtocol() it returns the protocol of the URL. Description Client power. public String getHost() it returns the host name of the URL. public getPort() (VB, Developer/2000, it returns the Port Number of the URL. RADString development PowerBuilder). public String getFile() it returns the file name of the URL. Client is responsible forit returns data the access applying business i.e. logic and public URLConnection instance of URLConnection presentation of data openConnection() associated with this URL. Only service provided by Server was that of database server. Check Program : URLDemo.java URLConnection Class The Java URLConnection class represents a communication link Initially two architecture (client server applications) between thetier URL and the application. This class can be used to read and write data to the specified resource referred by the URL. Around since the mid-80s. How get the object of URLConnection class Clienttopower. The openConnection() method of URL class returns the object of URLConnection RAD developmentclass. (VB, Developer/2000, PowerBuilder). Client is responsible for data access applying business logic and Syntax: presentation of data public URLConnection openConnection()throws IOException{} Only service provided by Server was that of database server. URLConnection Class (cont…) This class contains the following methods Initially two tier architecture (client server applications) • Around Long since getDate( ); the mid-80s. • Long getLastModified( ); • Client Longpower. getContentLength( ); • InputStreamgetInputStream( ); RAD development (VB, Developer/2000, PowerBuilder). Client is responsible for data access applying business logic and presentation of data OnlyProgram service: provided by Server was that of database server. Check DisplayData.java Java HttpURLConnection class The Java HttpURLConnection class is http specific URLConnection. It works for HTTP protocol only. By the help of HttpURLConnection class, you can information of any HTTP URL such as header information, status code, response code etc. The java.net.HttpURLConnection is subclass of URLConnection class. The openConnection() method of URL class returns the object of URLConnection class. Syntax: public URLConnection openConnection()throws IOException{} You can typecast it to HttpURLConnection type as given below. URL url=new URL("http://www.marwadiuniversity.ac.in"); HttpURLConnection huc=(HttpURLConnection)url.openConnection(); Check Programs : HttpURLConnectionDemo.java InetAddress Class Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of any host name for example www.javatpoint.com, www.google.com, www.facebook.com etc. InetAddress Class cont.. Commonly used methods of InetAddress class Method Description public static InetAddress getByName(String host) throws UnknownHostException it returns the instance of InetAddress containing LocalHost IP and name. public static InetAddress getLocalHost() throws UnknownHostException it returns the instance of InetAdddress containing local host name and address. public String getHostName() it returns the host name of the IP address. public String getHostAddress() it returns the IP address in string format. Check Programs : InetDemo.java Local vs Remote method invocation Remote Method Invocation (RMI) 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. RMI System Architecture Built in three layers (they are all independent): ✓ Stub/Skeleton layer ✓ Remote reference layer ✓ Transport layer Remote Method Invocation (RMI) The interface between the application layer and the rest of the system Stubs and skeletons are generated using the RMIC compiler This layer transmits data to the remote reference layer via the abstraction of marshal streams (that use object serialization) This layer doesn’t deal with the specifics of any transport 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: 1. It initiates a connection with remote Virtual Machine (JVM), 2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM), 3. It waits for the result 4. It reads (unmarshals) the return value or exception, and 5. 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: 1. It reads the parameter for the remote method 2. It invokes the method on the actual remote object, and 3. It writes and transmits (marshals) the result to the caller. In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons. The Remote Reference Layer The middle layer Provides the ability to support varying remote reference or invocation protocols independent of the client stub and server skeleton Example: the unicast protocol provides point-to-point invocation, and multicast provides invocation to replicated groups of objects, other protocols may deal with different strategies… The Transport Layer A low-level layer that ships serialized objects between different address spaces Responsible for: Setting up connections to remote address spaces Managing the connections Listening to incoming calls Maintaining a table of remote objects that reside in the same address space ✓ Setting up connections for an incoming call ✓ Locating the dispatcher for the target of the remote call ✓ ✓ ✓ ✓ How does RMI work? An invocation will pass through the stub/skeleton layer, which will transfer data to the remote reference layer The semantics of the invocation are carried to the transport layer The transport layer is responsible for setting up the connection The Naming Registry The remote object must register itself with the RMI naming registry A reference to the remote object is obtained by the client by looking up the registry Java RMI Example The 6 steps to write the RMI program. 1. Create the remote interface 2. Provide the implementation of the remote interface 3. Compile the implementation class and create the stub and skeleton objects using the rmic tool 4. Start the registry service by rmiregistry tool 5. Create and start the remote application 6. Create and start the client application Java RMI Example Execution Steps For running rmi example, 1) compile all the java files javac *.java 2)create stub and skeleton object by rmic tool rmic AdderRemote 3)start rmi registry in one command prompt rmiregistry 5000 4)start the server in another command prompt java MyServer 5)start the client application in another command prompt java MyClient Check Program : rmi1 END OF UNIT - 1