Networking in java
E N D
Presentation Transcript
NETWORKING IN JAVA 2021 2021 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: 1.Sharing resources 2.Centralize software management The java.net package supports two protocols, 1.TCP: Transmission Control Protocol provides reliable communication between the sender and receiver. TCP is used along with the Internet Protocol referred as TCP/IP. 2.UDP: User Datagram Protocol provides a connection-less protocol service by allowing packet of data to be transferred along two or more nodes Java Networking Terminology The widely used Java networking terminologies are given below: 1.IP Address 2.Protocol 3.Port Number 4.MAC Address 5.Connection-oriented and connection-less protocol 6.Socket 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. LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 2)Protocol A protocol is a set of rules basically that is followed for communication. For example: oTCP oFTP oTelnet oSMTP oPOP 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. 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 address. For example, an Ethernet card may have a MAC address of 00:0d:83::b1:c0:8e. 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. 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 communications. Visit next page for Java socket programming. java.net package The java.net package can be divided into two sections: 1.A Low-Level API: It deals with the abstractions of addresses i.e. networking identifiers, Sockets i.e. bidirectional data communication mechanism and Interfaces i.e. network interfaces. 2.A High Level API: It deals with the abstraction of URIs i.e. Universal Resource Identifier, LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 URLs i.e. Universal Resource Locator, and Connections i.e. connections to the resource pointed by URLs. The java.net package provides many classes to deal with networking applications in Java. A list of these classes is given below: oAuthenticator oCacheRequest oCacheResponse oContentHandler oCookieHandler oCookieManager oDatagramPacket oDatagramSocket oDatagramSocketImpl oInterfaceAddress oJarURLConnection oMulticastSocket oInetSocketAddress oInetAddress oInet4Address oInet6Address oIDN oHttpURLConnection oHttpCookie oNetPermission oNetworkInterface oPasswordAuthentication oProxy oProxySelector oResponseCache oSecureCacheResponse oServerSocket oSocket LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 oSocketAddress oSocketImpl oSocketPermission oStandardSocketOptions oURI oURL oURLClassLoader oURLConnection oURLDecoder oURLEncoder oURLStreamHandler List of interfaces available in java.net package: oContentHandlerFactory oCookiePolicy oCookieStore oDatagramSocketImplFactory oFileNameMap oSocketOption<T> oSocketOptions oSocketImplFactory oURLStreamHandlerFactory oProtocolFamily 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: LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 1.IP Address of Server, and 2.Port number. In client and server communication, client sends a message to the server, server reads the message and prints it. Here, two classes are being used: Socket and ServerSocket. The Socket class is used to communicate client and server. Through this class, we can read and write message. The ServerSocket class is used at server-side. The accept() method of ServerSocket class blocks the console until the client is connected. After the successful connection of client, it returns the instance of Socket at server-side. Socket class A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket. LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 Important methods: Method Description 1) public InputStream getInputStream() returns the InputStream attached with this socket. 2) public OutputStream getOutputStream() returns the OutputStream attached with this socket. 3) public synchronized void close() closes this socket ServerSocket class 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) close() public synchronized void closes the server socket. Example of Java Socket Programming Creating Server: To create the server application, we need to create the instance of ServerSocket class. Here, we are using 6666 port number for the communication between the client and server. we may also choose any other port number. The accept() method waits for the client. If clients connects with the given port number, it returns an instance of Socket. ServerSocket ss=new ServerSocket(6666); ServerSocket ss=new ServerSocket(6666); Socket s=ss.accept();//establishes connection and waits for the Socket s=ss.accept();//establishes connection and waits for the LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 Creating Client: To create the client application, we need to create the instance of Socket class. Here, we need to pass the IP address or hostname of the Server and a port number. Here, we are using "localhost" because our server is running on same system. Socket s=new Socket("localhost",6666); A simple Java socket programming where client sends a text and server receives and prints it. import java.io.*; import java.net.*; public class MyServer { public static void main(String[] args){ try{ ServerSocket ss=new ServerSocket(6666); Socket s=ss.accept();//establishes connection DataInputStream dis=new DataInputStream(s.getInputStream()); String str=(String)dis.readUTF(); System.out.println("message= "+str); ss.close(); }catch(Exception e){System.out.println(e);} } } File: MyClient.java import java.io.*; import java.net.*; public class MyClient { public static void main(String[] args) { try{ Socket s=new Socket("localhost",6666); DataOutputStream dout=new DataOutputStream(s.getOutputStream()); dout.writeUTF("Hello Server"); LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 dout.flush(); dout.close(); s.close(); }catch(Exception e){System.out.println(e);} }} Example of Java Socket Programming (Read-Write both side): In this example, client will write first to the server then server will receive and print the text. Then server will write to the client and client will receive and print the text. The step goes on. import java.net.*; import java.io.*; class MyServer{ public static void main(String args[])throws Exception{ ServerSocket ss=new ServerSocket(3333); Socket s=ss.accept(); DataInputStream din=new DataInputStream(s.getInputStream()); DataOutputStream dout=new DataOutputStream(s.getOutputStream()); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str="",str2=""; while(!str.equals("stop")){ str=din.readUTF(); System.out.println("client says: "+str); str2=br.readLine(); dout.writeUTF(str2); dout.flush(); } din.close(); s.close(); ss.close(); }} LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 import java.net.*; import java.io.*; class MyClient{ public static void main(String args[])throws Exception{ Socket s=new Socket("localhost",3333); DataInputStream din=new DataInputStream(s.getInputStream()); DataOutputStream dout=new DataOutputStream(s.getOutputStream()); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str="",str2=""; while(!str.equals("stop")){ str=br.readLine(); dout.writeUTF(str); dout.flush(); str2=din.readUTF(); System.out.println("Server says: "+str2); } dout.close(); s.close(); }} TCP/IP Socket Programming in Java TCP is a Network Protocol that stands for Transfer Control Protocol, which allows well-founded communication between applications. TCP is consistently used over the Internet Protocol, and that is why referred to as TCP/IP. The communication mechanism between two systems, using TCP, can be established using Sockets and is known as Socket Programming. Hence, socket programming is a concept of Network Programming, that suggests writing programs that are executed across multiple systems, which are connected to each other using a network. LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 The mechanism for Socket Programming A client creates a socket at its end of transmission and strives to connect the socket to the server. When a connection is established, the server creates a socket at its end and, the client and server can now ready communicate through writing and reading methods. Following is the elaborated procedure of what happens when a TCP connection is established: 1.An object of ServerSocket is instantiated, and desired port number is specified, on which connection is going to take place. 2.The accept method of ServerSocket is invoked, in order to hold the server in listening mode. This method won’t resume until a client is connected to the server through the given port number. 3.Now, on the client-side, an object of Socket is instantiated, and desired port number and IP address is specified for the connection. 4.An attempt is made, for connecting the client to the server using the specified IP address and port number. If the attempt is successful, the client is provided with a Socket that is capable of communicating to the respective server, with write and read methods. If unsuccessful, the desired exception is raised. 5.Since a client is connected to the server, accept method on the server-side resumes, providing a Socket that is capable of communicating to the connected client. 6.Once the communication is completed, terminate the sockets on both, the server and the client- side. Now, communication is held using input/output streams of Sockets. The InputStream of the client is coupled with the OutputStream of the server and the OutputStream of the client is coupled with the InputStream of the server. Since TCP is a two-way network protocol, hence information can flow through both the streams at the time. LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 Client-Side Programming For the Client machine, we need to now establish the socket connection. Socket Connection is when the two machines have information about each other’s network location (IP Address) and the TCP port. Connection: Socket socket = new Socket(IP Address, port number); //IP Address of the server, //TCP port number on which the server is listening Communication: The communication is held using the output and input streams. These streams are responsible for transmitting the information in the form of byte array. An object can also be transmitted through these streams, but it needs to be serialized before transmitting and deserialized after it has been received. Input and output streams are made available through socket instances. Terminating Connection: The socket connection needs to be terminated explicitly once the communication is fulfilled. Implementation: Below is the client-side implementation of socket programming in java. Import java.io.*; import java.net.*; class Client { public static void main(String data[]) {//data is taken as command line argument String ipAddress=data[0]; int portNumber=Integer.parseInt(data[1]); int rollNumber=Integer.parseInt(data[2]); String name=data[3]; String gender=data[4];String request=rollNumber+”,”+name+”,”+gender+”#”; //”#” acts as a terminatortry { Socket socket=new Socket(ipAddress , portNumber); // Socket is initialized and attempt is made for connecting to the and streams server// Declaring other properties LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 OutputStream outputStream; OutputStreamWriter outputStreamWriter; InputStream inputStream; InputStreamReader inputStreamReader; StringBuffer stringBuffer; String response; int x;// retrieving output Stream and its writer, for sending request or acknowledgement outputStream=socket.getOutputStream(); outputStreamWriter=new OutputStreamWriter(outputStream);outputStreamWriter.write(request); outputStreamWriter.flush(); // request is sent// retrieving input stream and its reader, for receiving acknowledgement or response inputStream=socket.getInputStream(); inputStreamReader=new InputStreamReader(inputStream); stringBuffer=new StringBuffer(); while(true) { x=inputStreamReader.read(); if(x==’#’ || x==-1) break; // reads till the terminator stringBuffer.append((char)x); }response=stringBuffer.toString(); System.out.println(response);socket.close(); //closing the connection }catch(Exception exception) { // Raised in case, connection is refused or some other technical issue System.out.println(exception); } }} Server-Side Programming For the server-side programming, a ServerSocket is required, which will wait for the client in the listening mode, on a particular TCP port. This ServerSocket holds until a Client Socket is connected successfully. As soon as the client is connected, another Socket comes into existence that will enable data sharing between the respective client and server. A temporary Socket is created to handle the request from that particular client and our main server socket will be free again, to listen to other requests. Hence we have ServerSocket and Socket on the server-side. Creating ServerSocket: The ServerSocket is instantiated on a specific port number. Then, the server starts listening for the client requests coming in for that port number. The accept method waits until a client connects to the server. After a successful connection, accept returns a Socket that will facilitate the communication. LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 Communication: For data transfer, the getOutputStream method is used to send the output through the socket, and input is received using getInputStream method. The Server keeps receiving messages until it receives the terminator. Terminating Connection: Once the response is sent, the socket, along with the input and output streams needs to be closed explicitly. Implementation: The Server implemented below is a multi-threaded server, so it can listen to multiple clients without any interruption. This works efficiently because, after establishing the connection, the server diverts the request, along with the respective socket, to another Thread or another Request Processor. The request processor will continue to work by using the socket, it received.Meanwhile, Server can listen to other requests coming in. As the connection is closed, the thread is also terminated. Example: import java.io.*; import java.net.*;class RequestProcessor extends Thread //for multi-threaded server { private Socket socket; RequestProcessor(Socket socket) { this.socket=socket; start(); // will load the run method }public void run() { try {//Declaring properties and streams OutputStream outputStream; OutputStreamWriter outputStreamWriter; / / / InputStream inputStream; InputStreamReader inputStreamReader; StringBuffer stringBuffer; // String response; String request;int x; int temp1,temp2; String part1,part2,part3; int rollNumber; String name; String gender;//getting input stream and its reader, for reading request or acknowledgement inputStream=socket.getInputStream(); inputStreamReader=new InputStreamReader(inputStream); stringBuffer=new StringBuffer(); while(true) { x=inputStreamReader.read(); if(x=='#' || x==-1) break; //reads until terminator stringBuffer.append((char)x); } LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 request=stringBuffer.toString(); System.out.println("Request : "+request);//parsing and extracting Request data temp1=request.indexOf(“,”); temp2=request.indexOf(“,”,temp1+1); part1=request.substring(0,temp1); part2=request.substring(temp1+1,temp2); part3=request.substring(temp2+1); rollNumber=Integer.parseInt(part1); name=part2; gender=part3; System.out.println("Roll number : "+rollNumber); System.out.println("Name : "+name); System.out.println("Gender : "+gender); temp2=request.indexOf(“,”,temp1+1); part1=request.substring(0,temp1); part2=request.substring(temp1+1,temp2); part3=request.substring(temp2+1); rollNumber=Integer.parseInt(part1); name=part2; gender=part3; System.out.println("Roll number : "+rollNumber); System.out.println("Name : "+name); System.out.println("Gender : "+gender); // handle data//sending response response="Data saved#";//get output stream and its writer, for sending response or acknowledgement outputStream=socket.getOutputStream(); outputStreamWriter=new OutputStreamWriter(outputStream);outputStreamWriter.write(response); outputStreamWriter.flush(); // response sent System.out.println("Response sent");socket.close(); //terminating connection }catch(Exception exception) { System.out.println(exception); }} }class Server { private ServerSocket serverSocket; private int portNumber;Server(int portNumber) { this.portNumber=portNumber; try {//Initiating ServerSocket with TCP port serverSocket=new ServerSocket(this.portNumber); startListening(); }catch(Exception e) { System.out.println(e); System.exit(0); } }private void startListening() { try { Socket socket; while(true) {System.out.println("Server is listening on port : "+this.portNumber); socket=serverSocket.accept(); // server is in listening mode LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 System.out.println("Request arrived..");// diverting the request to processor with the socket reference new RequestProcessor(socket); } }catch(Exception e) { System.out.println(e); } }public static void main(String data[]) { int portNumber=Integer.parseInt(data[0]); Server server=new Server(portNumber); }} Socket Programming with UDP UDP also allows two (or more) processes running on different hosts to communicate. However, UDP differs from TCP in many fundamental ways. First, UDP is a connectionless service -- UDP provides an unreliable transport service to its communication processes -- it makes no guarantees that a datagram will reach its ultimate destination. UDP client-server programming : there is (i) no initial handshaking between the two processes, and therefore no need for a welcoming socket, (ii) no streams are attached to the sockets, (iii) the sending hosts creates "packets" by attaching the IP destination address and port number to each batch of bytes it sends, and (iv) the receiving process must unravel to received packet to obtain the packet's information bytes. Recall once again our simple application: 1.A client reads a line from its standard input (keyboard) and sends the line out its socket to the server. 2.The server reads a line from its socket. 3.The server converts the line to uppercase. 4.The server sends the modified line out its socket to the client. 5.The client reads the modified line through its socket and prints the line on its standard output (monitor). UDPClient.java Here is the code for the client side of the application: import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } } The program UDPClient.java constructs one stream and one socket, as shown in Figure 1. The socket is called clientSocket, and it is of type DatagramSocket. Note that UDP uses a different kind of socket than TCP at the client. In particular, with UDP our client uses a DatagramSocket whereas with TCP our client used a Socket. The stream inFromUser is an input stream to the program; it is attached to the standard input, i.e., the keyboard. We had an equivalent stream in our TCP version of the program. When the user types characters on the keyboard, the characters flow into the stream inFromUser. But in contrast with TCP, there are no streams (input or output) attached to the socket. Instead of feeding bytes to stream attached to a Socket object, UDP will push individual packets through the DatagramSocket object. Figure 1: UDPClient.java has one stream and one socket. LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 Let's now take a look at the lines in the code that differ significantly from TCPClient.java. DatagramSocket clientSocket = new DatagramSocket(); The above line creates the object clientSocket of type DatagramSocket. In contrast with TCPClient.java, this line does not initiate a TCP connection. In particular, the client host does not contact the server host upon execution of this line. For this reason, the constructor DatagramSocket() does not take the server hostname or port number as arguments. Using our door/pipe analogy, the execution of the above line creates a door for the client process but does not create a pipe between the two processes. InetAddress IPAddress = InetAddress.getByName("hostname"); In order to send bytes to a destination process, we shall need to obtain the address of the process. Part of this address is the IP address of the destination host. The above line invokes a DNS look up that translates "hostname" (supplied in the code by the developer) to an IP address. DNS was also invoked by the TCP version of the client, although it was done there implicitly rather than explicitly. The method getByName() takes as an argument the hostname of the server and returns the IP address of this same server. It places this address in the object IPAddress of type InetAddress. byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; The byte arrays sendData and receiveData will hold the data the client sends and receives, respectively. sendData = sentence.getBytes(); The above line essentially performs a type conversion. It takes the string sentence and renames it as sendData, which is an array of bytes. DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); The above line constructs the packet, sendPacket, that the the client will pop into the network through its socket. This packet includes that data that is contained in the packet, sendData, the length of this data, the IP address of the server, and the port number of the application (which we have set to 9876). Note that sendPacket is of type DatagramPacket. LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 clientSocket.send(sendPacket); In the above line the method send() of the object clientSocket takes the packet just constructed and pops it into the network through clientSocket. Once again, note that UDP sends the line of characters in a manner very different from TCP. TCP simply inserted the line into a stream, which had a logical direct connection to the server; UDP creates a packet which includes the address of the server. After sending the packet, the client then waits to receive a packet from the server. DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); In the above line, while waiting for the packet from the server, the client creates a place holder for the packet, receivePacket, an object of type DatagramPacket. clientSocket.receive(receivePacket); The client idles until it receives a packet; when it does receive a packet, it puts the packet in receivePacket. String modifiedSentence = new String(receivePacket.getData()); The above line extracts the data from receivePacket and performs a type conversion, converting an array of bytes into the string modifiedSentence. System.out.println("FROM SERVER:" + modifiedSentence); The above, which is also present in TCPClient, prints out the string modifiedSentence at the client's monitor. clientSocket.close(); This last line closes the socket. Because UDP is connectionless, this line does not cause the client to send a tranport-layer message to the server (in contrast with TCPClient). UDPServer.java Let's now take a look at the server side of the application: import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket =new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } } } The program UDPServer.java constructs one socket, as shown in Figure 2. The socket is called serverSocket. It is an object of type DatagramSocket, as was the socket in the client side of the application. Once again, no streams are attached to the socket. Figure 2: UDPServer.java has one socket. LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 Let's now take a look at the lines in the code that differ from TCPServer.java. DatagramSocket serverSocket = new DatagramSocket(9876); The above line constructs the DatagramSocket serverSocket at port 9876. All data sent and received will pass through this socket. Because UDP is connectionless, we do not have to spawn a new socket and continue to listen for new connection requests, as done in TCPServer.java. If multiple clients access this application, they will all send their packets into this single door, serverSocket. String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); The above three lines unravel the packet that arrives from the client. The first of the three lines extracts the data from the packet and places the data in the String sentence; it has an analogous line in UDPClient. The second line extracts the IP address; the third line extracts the client port number, which is chosen by the client and is different from the server port number 9876. (We will discuss client port numbers in some detail in the next chapter). It is necessary for the server to obtain the address (IP address and port number) of the client, so that it can send the capitalized sentence back to the client. That completes our analysis of the UDP program pair. To test the application, you install and compile UDPClient.java in one host and UDPServer.java in another host. (Be sure to include the proper hostname of the server in UDPClient.java.) Then execute the two programs on their respective hosts. Unlike with TCP, you can first execute the client side and then the server side. This is because, when you execute the client side, the client process does not attempt to initiate a connection with the server. Once you have executed the client and server programs, you may use the application by typing a line at the client. LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 A comparison between TCP and UDP is given below as a table S.No: 1 2 3 4 5 TCP UDP TCP is connection oriented Reliable TCP is slower when compared with UDP TCP header size is 20 bytes Flow control is there Connection less Un-reliable Faster UDP header size is 8 bytes No flow control Java URL The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide Web. For example: 1.https://www.javatpoint.com/java-tutorial A URL contains many information: 1.Protocol: In this case, http is the protocol. 2.Server name or IP Address: In this case, www.javatpoint.com is the server name. 3.Port http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is not mentioned in the URL, it returns -1. Number: It is an optional attribute. If we write 4.File Name or directory name: In this case, index.jsp is the file name. Constructors of Java URL class URL(String spec): Creates an instance of a URL from the String representation. URL(String protocol, String host, int port, String file) Creates an instance of a URL from the given protocol, host, port number, and file. LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 URL(String protocol, String host, int port, String file, URLStreamHandler handler) Creates an instance of a URL from the given protocol, host, port number, file, and handler. URL(String protocol, String host, String file) Creates an instance of a URL from the given protocol name, host name, and file name. URL(URL context, String spec) Creates an instance of a URL by parsing the given spec within a specified context. URL(URL context, String spec, URLStreamHandler handler) Creates an instance of a URL by parsing the given spec with the specified handler within a given context. Commonly used methods of Java URL class The java.net.URL class provides many methods. The important methods of URL class are given below. Method Description public String getProtocol() it returns the protocol of the URL. public String getHost() it returns the host name of the URL. public String getPort() it returns the Port Number of the URL. public String getFile() it returns the file name of the URL. public String getAuthority() it returns the authority of the URL. public String toString() it returns the string representation of the URL. public String getQuery() it returns the query string of the URL. public String getDefaultPort() it returns the default port of the URL. public URLConnection openConnection() it returns the instance of URLConnection i.e. associated with this URL. LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 public boolean equals(Object obj) it compares the URL with the given object. public Object getContent() it returns the content of the URL. public String getRef() it returns the anchor or reference of the URL. public URI toURI() it returns a URI of the URL. Example of Java URL class 1.//URLDemo.java 2.import java.net.*; 3.public class URLDemo{ 4.public static void main(String[] args){ 5.try{ 6.URL url=new URL("http://www.javatpoint.com/java-tutorial"); 7.System.out.println("Protocol: "+url.getProtocol()); 8.System.out.println("Host Name: "+url.getHost()); 9.System.out.println("Port Number: "+url.getPort()); 10.System.out.println("File Name: "+url.getFile()); 12. 13.}catch(Exception e){System.out.println(e);} 14. } 15. } 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. An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress represents the IP address with its corresponding host name. There are two types of addresses: Unicast and Multicast. The Unicast is an identifier for a single interface whereas Multicast is an identifier for a set of interfaces. Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host name resolutions. LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 IP Address An IP address helps to identify a specific resource on the network using a numerical representation. Most networks combine IP with TCP (Transmission Control Protocol). It builds a virtual bridge among the destination and the source. There are two versions of IP address: 1.IPv4 IPv4 is the primary Internet protocol. It is the first version of IP deployed for production in the ARAPNET in 1983. It is a widely used IP version to differentiate devices on network using an addressing scheme. A 32-bit addressing scheme is used to store 232 addresses that is more than 4 million addresses. Features of IPv4: oIt is a connectionless protocol. oIt utilizes less memory and the addresses can be remembered easily with the class based addressing scheme. oIt also offers video conferencing and libraries. 2.IPv6 IPv6 is the latest version of Internet protocol. It aims at fulfilling the need of more internet addresses. It provides solutions for the problems present in IPv4. It provides 128-bit address space that can be used to form a network of 340 undecillion unique IP addresses. IPv6 is also identified with a name IPng (Internet Protocol next generation). Features of IPv6: oIt has a stateful and stateless both configurations. oIt provides support for quality of service (QoS). oIt has a hierarchical addressing and routing infrastructure. TCP/IP Protocol LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 oTCP/IP is a communication protocol model used connect devices over a network via internet. oTCP/IP helps in the process of addressing, transmitting, routing and receiving the data packets over the internet. oThe two main protocols used in this communication model are: 1.TCP i.e. Transmission Control Protocol. TCP provides the way to create a communication channel across the network. It also helps in transmission of packets at sender end as well as receiver end. 2.IP i.e. Internet Protocol. IP provides the address to the nodes connected on the internet. It uses a gateway computer to check whether the IP address is correct and the message is forwarded correctly or not. Java InetAddress Class Methods 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. LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.
NETWORKING IN JAVA 2021 2021 Example of Java InetAddress Class Let's see a simple example of InetAddress class to get ip address of www.google.com website. InetDemo.java import java.io.*; 1.import java.net.*; 2.public class InetDemo{ 3.public static void main(String[] args){ 4.try{ 5.InetAddress ip=InetAddress.getByName("www.google.com"); 6. System.out.println("Host Name: "+ip.getHostName()); 7.System.out.println("IP Address: "+ip.getHostAddress()); 8.}catch(Exception e){System.out.println(e);} 10. } 11. } LAKSHMI.S, SRI ADI CHUNCHANAGIRI WOMENS COLLEGE, CUMBUM.