Java network programming


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

The J2SE API in the java.net package contains classes and interfaces that provide low-level communication details. You can use these classes and interfaces directly to focus on solving problems rather than on communication details.

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

  • TCP: TCP is the abbreviation of Transmission Control Protocol, It guarantees reliable communication between two applications. Commonly used for Internet protocols, known as TCP/IP.

  • UDP: UDP is the abbreviation of User Datagram Protocol, a connectionless protocol. Provides packets of data to be sent between applications.

This tutorial mainly explains the following two topics.

  • Socket Programming: This is the most widely used networking concept and it has been explained in great detail

  • URL Processing: This part will be discussed in another space. Click here to learn more about URL processing in the Java language.


Socket Programming

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

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

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

The following steps occur when establishing a TCP connection using sockets between two computers:

  • The server instantiates a ServerSocket object, which represents communication through a port on the server.

  • The server calls the accept() method of the ServerSocket class, which waits until the client connects to the 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 attempts to connect the client to the specified server and port number. If communication is established, a Socket object is created on the client to communicate with the server.

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


#After the connection is established, communication is carried out using I/O streams. Each socket has an output stream and an input stream. The client's output stream is connected to the server's input stream, and the client's input stream is connected to the server's output stream.


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


Methods of the ServerSocket class

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

The 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
Creates a server socket using the specified backlog and binds it to the specified local port number.
3public ServerSocket(int port, int backlog, InetAddress address) throws IOException
Creates a server with the specified port, listening backlog, and local IP address to bind to.
4public ServerSocket() throws IOException
Create an unbound server socket.

Create an unbound server socket. If 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 methods of the ServerSocket class:

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

Methods of the Socket class

The java.net.Socket class represents the socket used by both the client and the server to communicate with each other. The client obtains a Socket object through instantiation, and 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.
Creates a stream socket and connects it to the specified port number on the specified host.
2public Socket(InetAddress host, int port) throws IOException
Creates a stream socket and connects it to the specified port number at 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 SocketImpl

When the Socket constructor returns, it does not simply instantiate 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 the server have a Socket object, so both the client and the 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 this socket is connected to, or null if not connected.
6public InputStream getInputStream() throws IOException
Returns the input stream for this socket.
7public OutputStream getOutputStream() throws IOException
Returns the output stream for this socket.
8public void close() throws IOException
Close this socket.

Methods of the InetAddress class

This class represents the Internet Protocol (IP) address. The following is a list of the more useful methods for Socket programming:

Serial numberMethod description
1static InetAddress getByAddress(byte[] addr)
Returns an InetAddress object given the original IP address.
2static InetAddress getByAddress(String host, byte[] addr)
Creates an InetAddress based on the provided hostname and IP address.
3static InetAddress getByName(String host)
Determines the IP address of a host given a hostname.
4String getHostAddress()
Returns the IP address string as a text representation.
5String getHostName()
Get the hostname of this IP address.
6static InetAddress getLocalHost()
Return localhost.
7String toString()
Convert this IP address to a String.

Socket Client Example

The following GreetingClient is a client program that connects to the server through socket and sends a request, and then Wait 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 Server Example

The following GreetingServer 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 above java code, and execute the following command to start the service, using the port number 6066:

$ java GreetingServer 6066
Waiting for client on port 6066...
Start the client as follows:
$ 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!