Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java network programming


May 10, 2021 Java


Table of contents


Java network programming

Network programming is the writing of programs that run on multiple devices (computers) that are connected over the network.

java.net the J2SE API in the package contains classes and interfaces that 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 support for two common network protocols is available in the package:

  • TCP: TCP is an abbreviation for the transport control protocol, which guarantees reliable communication between the two applications. Typically used in Internet protocols, it is called TCP/IP.
  • UDP: UDP is an abbreviation for the user data report protocol, a protocol without a connection. Provides packets of data to be sent between applications.

This tutorial focuses on the following two topics.

  • Socket programming: This is the most widely used network concept, and it has been explained in great detail
  • URL Processing: This section will be discussed in a separate section, click here to learn more about URL processing in the Java language.

Socket programming

The socket uses TCP to provide a communication mechanism between the two computers. The client program creates a socket and attempts to connect to the server's socket.

When the connection is established, the server creates a Socket object. Clients and servers can now communicate by writing and reading Socket objects.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for server programs to listen to and connect clients.

The following steps occur when a TCP connection is made using a socket between two computers:

  • The server instantiates a ServerSocket object, which represents communication through the ports on the server.
  • The server calls the accept() method of the ServerSocket class, which waits until the client connects to a given port on the server.
  • While the server is waiting, a client instantiates a Socket object, specifying the server name and port number to request a connection.
  • The constructor of the Socket class tries to connect the client to the specified server and port number. If communication is established, creating a Socket object on the client side can communicate with the server.
  • On the server side, the accept() method returns a new socket reference on the server that connects to the client's socket.
After the connection is established, communication is made by using the I/O flow. E ach socket has an output stream and an input stream. T he output stream of the client is connected to the input stream on the server side, while the input stream of the client is connected to the output stream on the server side.

TCP is a two - way communication protocol, so data can be sent at the same time through two streams. H ere's a complete set of useful ways to implement sockets that some classes provide.


The method of the ServerSocket class

The server application gets a port by using the java.net.ServerSocket class and listens for client requests.

The ServerSocket class has four construction methods:

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

Create an unbound server socket. I f the ServerSocket construction method does not throw an exception, it means that your application has successfully bound to the specified port and is listening for client requests.

Here are some common ways to use the ServerSocket class:

Serial number Method description
1 public int getLocalPort()
Returns the port on which this socket is listening.
2 public Socket accept() throws IOException
Listen for and accept the connection to this socket.
3 public void setSoTimeout(int timeout)
Enable/disable the SO_TIMEOUT timeout values, in milliseconds.
4 public void bind(SocketAddress host, int backlog)
Bind ServerSocket to a specific address (IP address and port number).

The method of the Socket class

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

The Socket class has five construction methods.

Serial number Method description
1 public Socket(String host, int port) throws UnknownHostException, IOException.
Create a stream socket and connect it to the specified port number on the specified host.
2 public Socket(InetAddress host, int port) throws IOException
Create a stream socket and connect it to the specified port number of the specified IP address.
3 public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException.
Create a socket and connect it to the specified remote port on the specified remote host.
4 public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException.
Create a socket and connect it to the specified remote port on the specified remote address.
5 public Socket()
Create an unnected socket with socketImpl, the system's default type

When the Socket construction method returns, and there is no simple instantiation of a Socket object, it actually attempts to connect to the specified server and port.

Here are some methods of interest, noting that both the client and the server have a Socket object, so both the client and the server can call them.

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

The method of the InetAddress class

This class represents an Internet Protocol (IP) address. Here's a list of some of the more useful methods for Socket programming:

Serial number Method description
1 static InetAddress getByAddress(byte[] addr)
The InetAddress object is returned given the original IP address.
2 static InetAddress getByAddress(String host, byte[] addr)
Create InetAddress based on the host name and IP address provided.
3 static InetAddress getByName(String host)
Determines the IP address of the host given the host name.
4 String getHostAddress()
Returns the IP address string, expressed in text.
5 String getHostName()
Gets the host name for this IP address.
6 static InetAddress getLocalHost()
Return to the local host.
7 String toString()
Convert this IP address to String.

Socket client instance

The following GreenClient is a client program that connects to the server via socket and sends a request, waiting for a response.

// 文件名 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("Connecting to " + serverName
                             + " on port " + port);
         Socket client = new Socket(serverName, port);
         System.out.println("Just connected to "
                      + 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 says " + in.readUTF());
         client.close();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

Socket service-side instance

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

// 文件名 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 client on port " +
            serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            System.out.println("Just connected to "
                  + 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 to "
              + 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.start();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

Compile the java code above and execute the following command to start the service, using port number 6066:

$ java GreetingServer 6066
Waiting for client on port 6066...
Turn on the client like this:
$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!