Networking in JAVA

Introduction to Networking

 To implement networking in Java, java.net package classes, that to IP address, and a range of methods related to TCP UDP, and URL. IO stream classes are also used to write data from and to communication channels. A virtual- -stream is provided by TCP, which supports IP connection across the network. The virtual stream supports the IO stream to transport data from and to either of the connections. Two important classes participate in communication. The InetAddress class provides the IP address of the target connection. The socket class is used to create a TCP connection. Once a connection has been created, bind both the end socket with their streams and communication will start by writing and reading data on these streams to and from remote applications.

Networking means transmitting data from one device to another device on the network, but both devices must use the same protocol for transmission.

There is an array of stacks, called protocol stack that involves everything from giving the data to the physical device by converting that voltage pulse to delivering data streams to applications for which it was destined. Each layer provides an abstraction and is dedicated to a specific fixed set of jobs. The intermediate layers also work as an interface between its upward and downward layers, first and the last. The two most famous and important network stacks are given below:

Each layer communicates only with its immediate above and below layers. Encapsulation and decapsulation are two mechanisms, that embed each layer's packets into the immediately below layer packet, and reverse the process 'as the data moves up at the receiving machine, respectively. The internet is a bunch of networks of different types of environments. The internet is exclusively the worldwide set of connections of TCP/IP networks that use IP addresses and protocols under the ultimate command.

SOCKETS

A Socket represents a TCP connection with a machine on the network. This class facilitates establishing the stream-based channel with a remote machine. For TCP/IP communication, there is a need to create a Socket with the remote machine. The class Socket creates a socket automatically establishes a TCP Connection, and throws an exception if it fails. Socket address is the combination of two components; one is host-id, which can refer to the hostname, IP address, and port number. The port number is an integer value that lies between 1 and 65536. In fact, on every host, there are 655636 different addresses. But there must be a server, and dynamically listening on the specified port.

There are two constructors of the Socket class. Creating a Socket object automatically connects to the given host and port. As earlier given, a server actively listens to the request, but as the connection is refused an IOException will be thrown, and an unknown hostname can be other possibilities of connection failure.

Socket(String hostName, int portNumber) throws IOException creates a Socket object, and connects to the given host on the given port number.

Socket sckt = new Socket ("mymac", 1889);

Socket(InetAddress hostAddress, int portNumber) throws I0Exception creates a Socket object, and connects to the given host address on the given port number.

InetAddress mac = InetAdodress. getByName ( "127.0.0.1");

Socket sckt = new Socket(mac.getaddress, 1889) ;

OR

Socket sckt = new Socket ("127.0.0.1", 1889);

Socket class methods provide the identification of the remote host, and port number of the remote and local host; also give the stream for communication. First, create the Socket object to perform communications across a TCP connection. After creating the socket, bind it with the required or corresponding stream with the help of getInputStream() and getOutputStream() methods to communicate with the remote server. The client and server will have both a lnputStrèam and an OutputStream for the purposes of communication.

Methods of java.net.Socket class

INTERNET ADDRESSING

TCP/IP is the architecture, implemented on the internet. The foundation of the TCP/IP is the IP (internetworking protocol). IP works on 3rd layer of the architecture, i.e. network layer. The application of IP addresses hosts and routing data packets (also called datagrams) between them. There are two versions of IP, IPv4 and IPv6. IPv4 contains a 32-bit long address, while IPv6 contains a 128-bit long address.

IPv4 format is XX.XX.XX.XX, where each two consecutive 'x (xx) separated by dot (.) are one byte, such as 168.196.12.1. Every IP address belongs to any network. Network falls into five different classes. The class can be used to determine the number of hosts in the network of which it is a member.

Class A: 1 - 126 (16M hosts)

Class B: 128 – 191 (65536 hosts each)

Class C: 192-223 (256 hosts each)

Class D: 224- 239 (addresses for multicasting)

Class E: 240- 255 (addresses reserved for future use)

The class defines the network size of the organization.

An IP datagram contains a header and a protocol data unit (PDU). The header collections of information about fragmentation, length, time to live (TTL), and similar parameters. The PDU contains the encapsulated data at the hosts which form routing decisions.

Transmission Control Protocol (TCP) is a connection-oriented protocol that is on top of IP. TCP packets, called segments, are encapsulated with an IP datagram. Encoding of TCP occurs at the endpoint of the communication channel, i.e. at hosts. Routers inspect the IP packets to route TCP encoding and decoding occur at the hosts which form routing decisions.

TCP provides guaranteed data transmission at the destination host's application because of its connection-oriented features. TCP is not responsible for the exact arrival time, or transfer rate at which data will be sent to the remote end, only gives surety about the delivery of uncorrupted and in-order data.

User Datagram Protocol (UDP) is a connectionless transport layer protocol that is on top of IP. It doesn't provide state management and data integrity functions. It also does not provide any congestion avoidance and packet delivery guarantee facility. If any received packed is corrupted it simply throws it away.

 NETWORK CLASSES AND INTERFACE

For networking, java uses the java.net package. The classes contained in the java.net package are listed below:

The java.net package's interfaces are listed here:

UnknownHostException is a subclass of IOException and indicates that the named host could not be successfully identified.

INET ADDRESS

The computer on the internet is identified by IP address, which is currently in two versions with different sizes in IPv4, it is 32-bit long (four bytes), and in IPv6, it is 128-bit long (eight bytes). InetAddress provides an abstraction to access the IP address that is shown in the figure given below.

There is no constructor for this class. The class provides some static methods to create the instance of the class, i.e. an object

Methods of java.net. InetAddress class

The methods given below provide the information from an InetAddress object:

 Methods of java.net.InetAddress class

UnknownHostException is a subclass of IOException and indicates that the named host could not be successfully identified.


}

FACTORY METHODS

The InetAddress class has no visible constructors. To create a lnetAddress object, we have to use one of the available factory methods. Factory methods are simply a convention while the static methods in a class return an instance of that class. Three commonly used lnetAddress factory methods are shown here:

Method: static InetAddress getLocalHost() throws UnknownHostException

Description: It returns the InetAddress object that represents the local host.

Method: static InetAddress getBy Name(String hostName) throws UnknownHostException

Description: It returns an InetAddress for a hostname passed to it.

Method: static InetAddress[]getAllBy Name(String hostName) throws UnknownHostException

Description: It returns an array of InetAddresses that represent all of the addresses that a particular name resolves to

INSTANCE METHODS

The InetAddress class also has several other methods, that can be used on the objects returned by the methods just discussed. Some of the most commonly used methods are:

Method: boolean equals(Object other)

Description: It returns true if this object has the same Internet address as the other.

Method: byte[]getAddress()

Description: It returns a byte array that represents the object's Internet address in network byte order.

Method: String getHostAddress()

Description: It returns a string that represents the host address associated with the InetAddressobject.

Method: String getHost Name( )

Description: It returns a string that represents the hostname associated with the InetAddress object.

Method: boolean isMulticastAddress( )

Description: It returns true if this Internet address is a multicast address. Otherwise, it returns false.

Method: String toString( )

Description: It returns a string that lists the hostname and the IP address for convenience.

 

TCP/IP CLIENT SOCKETS

TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point, stream-based connections between hosts on the Internet. A socket can be used to connect Java's I/O system to other programs that may reside either on the local machine or on any other machine on the Internet. Applets can also establish socket connections back to the host from which the applet was downloaded. There are two kinds of TCP sockets in Java. One is for the servers, and the other is for the clients. The ServerSocket class is designed to be a "listener." which waits for clients to connect before doing anything. The Socket class is designed to connect to server sockets and initiate protocol exchanges. The creation of a Socket object establishes a connection between the client and the server. The constructors that are used to create client sockets are:

Method: Socket(String hostName, int port)

Description: It creates a socket connecting the local host to the named host and port and can throw an UnknownHostException or an IOException.

Method: Socket(InetAddress ipAddress, int port)

Description: It creates a socket using a preexisting InetAddress object and a port and can throw an IOException.

A socket can be examined at any time for the address and port information associated with it with the help of the following methods:

Method: InetAddress getInetAddress( )

Description: It returns the InetAddress associated with the Socket object.

Method: int getPort()

Description: It returns the remote port to which this Socket object is connected.

Method: int getLocalPort( )

Description: It returns the local port to which this Socket object is connected.

Once the Socket object has been created, it can also be examined to gain access to the input and output streams associated with it. Each of these methods can throw an IOException if the sockets have been invalidated by a loss of connection on the Net. The streams are:

Method: InputStream getlnputStream()

Description: It returns the InputStream associated with the invoking socket.

Method: OutputStreamgetOutputStream()

Description: It returns the OutputStream associated with the invoking socket.

 

TCP/IP SERVER SOCKETS

The ServerSocket class is used to create servers that listen for either local or remote client programs to connect to them on various published ports. ServerSockets are quite different from normal Sockets. When we create a Seversocket, it will register itself with the system as having an interest in client connections. The constructors for ServerSocket reflect the port number that we wish to accept connections on and how long we want the queue for said port to be. The queue length tells the system how many client connections it can leave pending before it should simply refuse connections. The default is 50. The constructors throw IOException under adverse conditions. The constructors are:

Method: ServerSocket(int port)

Description: It creates a server socket on the specified port with a queue length of 50.

Method: ServerSocket(int port, int maxQueue)

Description: It creates a server socket on the specified port with a maximum queue length of maxQueue.

Method: ServerSocket(int port, int maxQueue, InetAddress localAddress)

Description: It creates a server socket on the specified port with a maximum queue length of maxQueue.

On a multihomed host, localAddress specifies the IP address to which IP address to which this socket bonds. ServerSocket has a method called accept(), which acts as a blocking call that will wait for a client to initiate communications, and then return with a normal Socket which is then used for communication client.

DATAGRAM

Datagrams are the bundles of information that is passed between machines. Once the datagram has been released to its intended target, there is no assurance that it will arrive or even that someone will be there to catch it. When the datagram is received, there is no assurance that it has not been damaged in transit or that whoever sent it is still there to receive a response. Java implements datagrams on top of the UDP protocol by using two classes:

The DatagramPacket object is the data container.

The DatagramSocket is the mechanism used to send or receive the DatagramPackets.

 Datagram Packet

The constructor specifies a buffer that will receive data and the size of a packet. It is used for receiving data over a DatagramSocket. Another form allows us to specify an offset into the buffer at which the data will be stored. A different form specifies a target address and port, which are used by a DatagramSocket to determine where the data in the packet will be sent. A still other form transmits packets beginning at the specified offset into the data. The different constructors are:

DatagramPacket (byte data[ ], int size)

DatagramPacket (byte đata[ ], int offset, int size)

DatagramPacket (byte data[ ], int size, InetAddress ipAđdress, int port)

DatagramPacket (byte data [], int offset, int size, InetAddress, ípAddress, int port)

There are several methods for accessing the internal state of a DatagramPacket. They give complete access to the destination address and port number of a packet, as well as the raw data and its length. Some of the most commonly used methods are:

Method: InetAddress getAddress()

Description: It returns the destination InetAddress, typically used for sending.

Method: int getPort( )

Description: It returns the port number.

Method: byte [] getData( )

Description: It returns the byte array of data contained in the datagram. It is mainly used to retrieve data from the datagram after it has been received.

Method: int getLength( )

Description: It returns the length of the valid data contained in the byte array that would be returned from the getData( ) method. This typically does not equal the length of the whole byte array.

IMPLEMENTING SERVERS

To implement networking in Java, java.net package classes, give access to IP addresses, and a range of methods related to TCP, UDP, and URL. IO stream classes are also used to read and write data from and to communication channels.

A virtual stream is provided by TCP, which supports IP connection across the network. The virtual stream supports the IO stream to transport data from and to either of the connections.

Two important classes participate in communication. InetAddress class is used to provide the IP address of the target connection. The socket class is used to create a TCP connection.

A virtual stream is provided by TCP, which supports IP connection across the network.

Once a connection has been created, we bind both ends of a socket with their streams, and communication will start by writing and reading data on these streams to and from remote applications.

Before looking at the implementation of the server, look at the classes of java.net that are used to implement a server:

(i) Classs InetAddress

Computer on the internet is identified by IP addresses, that are currently in two versions with different sizes, in IPv4, it is 32-bit long (four bytes), and in IPv6, it is 128-bit long (eight bytes). InetAddress provides an abstraction to access the IP address that is shown in the figure below.

There is no constructor for this class. The class provides some static methods to create the instance of the class, i.e. an object.

(ii) Class ServerSocket

The ServerSocket class provides the facility by which a server accepts a connections request from clients across the network. The class creates a Socket for individual client connection. After socket creation, an InputStream and an OutputStream will be created for communicating with client. The fundamental mechanism for implementing a server is to open a ServerSocket with a specific and certain local port number. The ServerSocket will start to wait for connections. As client generates the request to connect to this port, the connection will be established.

ServerSocket is constructed by choosing a port on the local machine. This port number should be in the range 1-65536; however, ports 1- 1023 are reserved for system services and can be used only by the machine administrator.

(ii) Class ServerSocket

The ServerSocket class provides the facility by which a server accepts a connection request from clients across the network. The class creates a Socket for individual client connections. After socket creation, an InputStream and an OutputStream will be created for communicating with the client. The fundamental mechanism for implementing a server is to open a ServerSocket with a specific and certain local port number. The ServerSocket will start to wait for connections. As the client generates the request to connect to this port, the connection will be established.

ServerSocket is constructed by choosing a port on the local machine. This port number should be in the range 1-65536; however, ports 1- 1023 are reserved for system services and can be used only by the machine administrator.

A server accepts the explicit connection request from a ServerSocket to obtain a client's Socket connection. As the ServerSocket is created, the operating system starts to accept the connections from clients, insert them in a queue, and delete one-by-one as the server calls the accept() method.

ServerSocket(int portNumber) throws IOException creates a ServerSocket object that listens on the specified port portNumber

ServerSocket Ssckt = new serverSocket (1889);

This server can listen on port 1889.

ServerSocket(int portNumber, int count Value) throws IOException creates a ServerSocket that listens on the specified port portNumber and countValue specifies the number of outstanding connection requests.

ServerSocket ssckt = new ServerSocket (1889, 40);

All these connections will be stored in a queue. Any connection requests more than the given value will be discarded. The default limit of the queue is 50 to accept connection requests. This server can listen on port 1889 and has 40 outstanding connection requests.

The methods given below allow connection to be accepted and information about the ServerSocket to be queried.

Methods of java.net. ServerSocket class



(iii) Class Socket

A Socket represents a TCP connection with a machine on the network. This class facilitates establishing the stream-based channel with a remote machine.

For TCP/IP communication, there is a need to create a Socket with the remote machine. The class Socket creates a socket that automatically establishes a TCP connection, and throws an exception if it fails. Socket address is the combination of two components: one is host-id, which refers to the hostname, IP address, and port number. The port number is an integer value that lies between 1 and 65536. In fact, on every host, there are 655636 different addresses. But there must be a server that dynamically listens on the specified port.

There are two constructors of the Socket class. Creating a Socket object automatically connects to the given host and port. As earlier stated, a server actively listens to the request, but as the connection is refused an IOException will be thrown, an unknown hostname can be another possibility of connection failure.

Socket(String hostName, int portNumber) throws IOException creates a Socket object, and connects to the given host on the given port number.

 Socket sckt= new Socket ("mymac", 1889);

Socket(InetAddress hostAddress, int portNumber) throws IOException creates a Socket object, and connects to the given host address on the given port number.

InetAddress mac= InetAddress.getByName ("127.0.0.1");

Socket sckt = new Socket (mac. getAddress, 1889);

OR

Socket sckt = new Socket ("127.0.0.1", 18 89);

Socket class methods provide the identification of the remote host, and port number of the remote and local host, and also give the stream for communication.

First, create the Socket object to perform communications across a TCP connection. After creating the socket, bind it with the required or corresponding stream with the help of getInput Stream() and getOutputStream() methods to communicate with the remote server. The client and server will have both an InputStream and an OutputStream for the purposes of communication.

Methods of java.net.Socket class




SENDING E-MAIL

A Socket will be created, and connected to port 25 which is the SMTTP port number. Simple Mail Transfer Protocol describes the format in which e-mail messages will be sent. In Unix-os, the sendmail daemon was already implemented to support these features.

MAKING URL CONNECTIONS  (CLICK ON THE TOPIC FOR THE SOURCE)

Methods of java.net.URL class


ADVANCED SOCKET PROGRAMMING 

Socket Timeouts

Whenever you try to read data from a socket, the read ( } call blocks as long as necessary to get enough bytes. By setting SO_TIMEOUT, you can ensure that the call will never be block for more than a fixed number of milliseconds. When the timeout expires, an InterruptedException is thrown, and you should be prepared to catch it, but still the socket is connected. Although this read () call can fail, you can try again to read from the socket. The next call may succeed. There are two methods given below to set and get the timeout value,

public synchronized void setSoTimeout (int milliseconds) throws

socketException

public synchronized int getSoTimeout ( ) throws SocketException

Example:

Sockett s = new Socket ();

s.setSoTimeout (10000); // time out after 10 seconds

s.connect(......);

Timeouts are given in milliseconds. Zero is interpreted as an infinite timeout, and is the default

value.

There is one another timeout issue, that is, the constructor 

Socket (String host, int port);

can block for uncertain period of time, until an initial connection is established.

The solution for this problem to make the Socket object in the following way:

Socket s = new Socket ( );

s.connect (new InetSocketAddress (host,port), time_out);

Similar option supported for ServerSocker is SO_TIMEOUT. SO_TIMEOUT is the amount of time, in milliseconds that accept() wait for an incoming connection before throwing a java.io.InterruptedlOException. If SO_TIMEOUT is 0, then accept() will never time out. The default is to never time out.

public void setSoTimeout (int timeout) throws Socket Exception

The setSoTimeout() method sets the SO_TIMEOUT field for the ServerSocket object. The countdown starts as accept() is invoked. When the timeout expires, accept() throws an InterruptedIOException. So, set this option before calling accept(); and the timeout value cannot be change while accept() is waiting for a connection. The timeout argument must be greater than Or equal to zero; if it isn't the method throws a llegalArgumentException.

Example 1:

try {

ServerSocket serversocket new ServerSocket (1148);

//block for no more than 20 seconds

server. setSoTimeout (20000) :

try {

Socket s = serversocket.accept ();

// handle the connection

//...

} catch (InterruptedIOException e) {

System. err.println ("No connection within 20 seconds);

} finally {

serversocket.close();

System. err.println ("Unexpected IOException :: "+ e);

}

Example 2:

// Create a socket without a timeout

try {

InetAđdress addr = InetAddress.getByName ("java. sun.com" );

int port = 80;

//This constructor will block until the connection succeeds

Socket socket = new Socket (addr, port);

} catch (UnknownHostException e )

} catch (IOException e)

//Create a socket with a timeout

try {

InetAddress addr = InetAddress.getByName (java.sun.com");

int port - 80

socketAddress sockaddr = new InetSocketAddress (addr, port) ;

//Create an unbound socket

Socket sock = new Socket ():

//This method will block no more than timeoutMs.

//If the timeout occurs, SocketTimeoutException is thrown. 

int timeoutMs = 2000; // 2 seconds

sock. connect (sockaddr, timeoutMs);

}catch (UnknownHostException e) {

} catch (SockettimeoutException e) {

) catch (IOException e) {

}

HALF-CLOSE

Whenever server receives a request from the client application, then it always determines the end of the request. Let's take an example, suppose the last request was for writing the data to a file, and now you just want to close the file at the end. But as you close the socket, you'll be disconnected from the server. The half-close is the solution to this problem. Using this, you can close the output stream of the socket, so that, no more request will goes to the server, but input stream will still open to receive and read the response from the server. There are two methods given below:

public void shutdownlnput() throws IOException method is used to close or shutdown input stream, cannot read data from the response.

public void shutdownOutput( ) throws IOException method is used to close or shutdown output stream, cannot generate the request to the server

Example:

Socket conn = null;

try {

Conn = new Socket ("www.indianrailway. gov. in", 80);

BufferedReader br = new BufferedReader ( new InputStreamReader (conn.get Input Stream () ) );

Writer out = new OutputStreamWriter (conn.getOutputStream( ), "UTF-8");

out.write("GET /HTTP 1.0");

connection. shutdownOutput( ); // now socket is half closed and can only read response data

String str;

while ((str = br.readLine ()) != null)

........

} catch (IOException e) { }

finally {

try{

if (conn I= null) conn.close ();

 } catch (IOException e) {

System.out.println (e); }

}

Additional Resources

A TUTORIAL ON SOCKET PROGRAMMING IN JAVA

  1. Books:
    • "Java: The Complete Reference" by Herbert Schildt
    • "Effective Java" by Joshua Bloch
  2. Online Courses:
    • Coursera - Java Programming and Software Engineering Fundamentals
  3. Video Tutorials:
    • Java Tutorial for Beginners by Programming with Mosh
    • Java Programming Tutorial - Full Course for Beginners by CodeWithChris
  4. Websites:
    • Oracle Java Documentation
    • GeeksforGeeks - Java Programming Language

No comments:

Post a Comment

Machine Learning