Java network programming

Posted by jamest on Tue, 08 Feb 2022 08:52:32 +0100

Java network programming

Network programming refers to writing programs that run on multiple devices (computers), which are connected through the network.

java.net package contains classes and interfaces, which provide low-level communication details. You can use these classes and interfaces directly to focus on solving problems without paying attention to communication details.

java.net package provides support for two common network protocols:

  • TCP: TCP (Transmission Control Protocol) is a connection oriented, reliable and byte stream based transport layer communication protocol. TCP layer is an intermediate layer above IP layer and below application layer. TCP guarantees reliable communication between two applications. Commonly used for Internet protocols, called TCP / IP.

  • UDP: UDP (English: User Datagram Protocol), located in the transport layer of OSI model. A connectionless protocol. Provides datagrams to be sent between applications. Because UDP lacks reliability and belongs to connectionless protocol, applications usually have to allow some lost, wrong or duplicate packets.

This tutorial focuses on the following two topics.

  • Socket programming: This is the most widely used network concept, which has been explained in great detail.

  • URL processing: this part will be discussed in another section. Click here to learn more about URL processing in Java language.

Socket programming

Sockets provide a communication mechanism between two computers using TCP. The client program creates a socket and tries to connect to the socket of the server.

When the connection is established, the server will create a Socket object. The client and server can now communicate by writing and reading Socket objects.

java. net. The socket class represents a socket, and Java net. The ServerSocket class provides a mechanism for server programs to listen to clients and establish connections with them.

The following steps appear when using sockets to establish a TCP connection between two computers:

  • The server instantiates a ServerSocket object to represent communication through the port on the server.

  • The server calls the accept() method of the ServerSocket class, which will wait until the client connects to the given port on the server.

  • When the server is waiting, a client instantiates a Socket object and specifies the server name and port number to request a connection.

  • The constructor of the Socket class attempts to connect the client to the specified server and port number. If the communication is established, create a Socket object on the client to communicate with the server.

  • On the server side, the accept() method returns a new socket reference on the server, which is connected to the socket of the client.

After the connection is established, the I/O stream is used for communication. Each socket has an output stream and an input stream. The output stream of the client is connected to the input stream of the server, and the input stream of the client is connected to the output stream of the server.

TCP is a two-way communication protocol, so data can be sent at the same time through two data streams The following is a complete set of useful methods provided by some classes to implement socket.

Method of ServerSocket class
The server application uses Java net. ServerSocket class to get a port and listen for client requests.

ServerSocket class has four construction methods:

Serial numberMethod description
1public ServerSocket(int port) throws IOException
Create a server socket bound to a specific port.
2public ServerSocket(int port, int backlog) throws IOException
Create a server socket with the specified backlog and bind it to the specified local port number.
3public ServerSocket(int port, int backlog, InetAddress address) throws IOException
Create a server using the specified port, listening backlog, and the local IP address to bind to.
4public ServerSocket() throws IOException
Creates an unbound server socket.

Creates an unbound server socket. If the ServerSocket constructor does not throw an exception, it means that your application has successfully bound to the specified port and listens for client requests.

Here are some common methods of ServerSocket class:

Serial numberMethod description
1public int getLocalPort()
Returns the port on which this socket listens.
2public Socket accept() throws IOException
Listen and accept connections to this socket.
3public void setSoTimeout(int timeout)
Enable / disable so by specifying a timeout value_ Timeout, in milliseconds.
4public void bind(SocketAddress host, int backlog)
Bind the ServerSocket to a specific address (IP address and port number).

Method of Socket class

java. net. The Socket class represents the Socket that both the client and the server use to communicate with each other. The client obtains a Socket object through instantiation, while the server obtains a Socket object through the return value of the accept() method.

The Socket class has five construction methods

Serial numberMethod description
1public Socket(String host, int port) throws UnknownHostException, IOException
Create a stream socket and connect it to the specified port number on the specified host.
2public Socket(InetAddress host, int port) throws IOException
Create a stream socket and connect it to the specified port number of the specified IP address.
3public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException.
Creates a socket and connects it to the specified remote port on the specified remote host.
4public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException.
Creates a socket and connects it to the specified remote port on the specified remote address.
5public Socket()
Create an unconnected socket through the system default type of SocketImpl

When the Socket constructor returns, instead of simply instantiating a Socket object, it will actually try to connect to the specified server and port.

Some interesting methods are listed below. Note that both the client and server have a Socket object, so both the client and server can call these methods.

Serial numberMethod description
1public void connect(SocketAddress host, int timeout) throws IOException
Connect this socket to the server and specify a timeout value.
2public InetAddress getInetAddress()
Returns the address of the socket connection.
3public int getPort()
Returns the remote port to which this socket is connected.
4public int getLocalPort()
Returns the local port to which this socket is bound.
5public SocketAddress getRemoteSocketAddress()
Returns the address of the endpoint to which this socket is connected, or null if it is not connected.
6public InputStream getInputStream() throws IOException
Returns the input stream for this socket.
7public OutputStream getOutputStream() throws IOException
Returns the output stream of this socket.
8public void close() throws IOException
Close this socket.

Method of InetAddress class

This class represents an Internet Protocol (IP) address. Here are some useful methods for Socket programming:
The InetAddress class does not provide a public constructor, but provides the following static methods to obtain the InetAddress instance

public static InetAddress getLocalHost()
public static InetAddress getByName(String host)

InetAddress provides the following common methods

public String getHostAddress(): return IP Address string (in text).
public String getHostName(): Get this IP Host name of the address
public boolean isReachable(int timeout): Test whether the address can be reached
InetAddress address_1 = InetAddress.getByName("www.baidu.com");
System.out.println(address_1);

System.out.println(address_1.getHostName());
//Get domain name
System.out.println(address_1.getHostAddress());
//Get IP

//Get local domain name and IP address
InetAddress address_2 = InetAddress.getLocalHost();

Socket client instance

The following greeningclient is a client program that connects to the server through socket, sends a request, and then waits for a response.

// File name: greetingclient java
 
import java.net.*;
import java.io.*;
 
public class GreetingClient
{
   public static void main(String [] args)
   {
      String serverName = args[0];
      int port = Integer.parseInt(args[1]);
      try
      {
         System.out.println("Connect to host:" + serverName + " ,Port number:" + port);
         Socket client = new Socket(serverName, port);
         System.out.println("Remote host address:" + client.getRemoteSocketAddress());
         OutputStream outToServer = client.getOutputStream();
         DataOutputStream out = new DataOutputStream(outToServer);
 
         out.writeUTF("Hello from " + client.getLocalSocketAddress());
         InputStream inFromServer = client.getInputStream();
         DataInputStream in = new DataInputStream(inFromServer);
         System.out.println("Server response: " + in.readUTF());
         client.close();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

Socket server instance

The following greeningserver program is a server-side application that uses Socket to listen to a specified port.

// File name: greetingclient java
 
import java.net.*;
import java.io.*;
 
public class GreetingClient
{
   public static void main(String [] args)
   {
      String serverName = args[0];
      int port = Integer.parseInt(args[1]);
      try
      {
         System.out.println("Connect to host:" + serverName + " ,Port number:" + port);
         Socket client = new Socket(serverName, port);
         System.out.println("Remote host address:" + client.getRemoteSocketAddress());
         OutputStream outToServer = client.getOutputStream();
         DataOutputStream out = new DataOutputStream(outToServer);
 
         out.writeUTF("Hello from " + client.getLocalSocketAddress());
         InputStream inFromServer = client.getInputStream();
         DataInputStream in = new DataInputStream(inFromServer);
         System.out.println("Server response: " + in.readUTF());
         client.close();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

Socket server instance

The following greeningserver program is a server-side application that uses Socket to listen to a specified port.

// File name: greetingserver java
 
import java.net.*;
import java.io.*;
 
public class GreetingServer extends Thread
{
   private ServerSocket serverSocket;
   
   public GreetingServer(int port) throws IOException
   {
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(10000);
   }
 
   public void run()
   {
      while(true)
      {
         try
         {
            System.out.println("Waiting for remote connection, port number:" + serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            System.out.println("Remote host address:" + server.getRemoteSocketAddress());
            DataInputStream in = new DataInputStream(server.getInputStream());
            System.out.println(in.readUTF());
            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("Thank you for connecting me:" + server.getLocalSocketAddress() + "\nGoodbye!");
            server.close();
         }catch(SocketTimeoutException s)
         {
            System.out.println("Socket timed out!");
            break;
         }catch(IOException e)
         {
            e.printStackTrace();
            break;
         }
      }
   }
   public static void main(String [] args)
   {
      int port = Integer.parseInt(args[0]);
      try
      {
         Thread t = new GreetingServer(port);
         t.run();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

Compile the above two java file codes and execute the following command to start the service. The port number is 6066:

$ javac GreetingServer.java 
$ java GreetingServer 6066

Waiting for remote connection, port number: 6066
Open a new command window and execute the above command to open the client:

$ javac GreetingClient.java 
$ java GreetingClient localhost 6066

Connect to host: localhost, port number: 6066
Remote host address: localhost/127.0.0.1:6066
Server response: Thank you for connecting me: / 127.0.0.1:6066
Goodbye!

Topics: Java