Java Network Programming

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

The J2SE APIs in the java.net package contain classes and interfaces that provide low-level communication details. You can use these classes and interfaces directly to focus on solving problems without worrying about communication details.

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

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

  • UDP: UDP (User Datagram Protocol) is located at the transport layer of the OSI model. It is a connectionless protocol. It provides datagrams for sending data between applications. Because UDP lacks reliability and is a connectionless protocol, applications usually must tolerate some lost, erroneous, or duplicate packets.

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 a separate section. Click here to learn more aboutURL handling in the Java language.。


Socket Programming

Sockets use TCP to provide a communication mechanism between two computers. A 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. The client and server can now communicate by writing to and reading from the Socket objects.

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

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

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

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

  • On the server side, the accept() method returns a new socket reference on the server, which 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 connects to the server's input stream, while the client's input stream connects to the server's output stream.

TCP is a bidirectional communication protocol, so data can be sent over both data streams at the same time. The following are some classes that provide a complete set of useful methods for implementing sockets.


ServerSocket Class Methods

Server applications use the java.net.ServerSocket class to obtain a port and listen for client requests.

The ServerSocket class has four constructors:

No. Method Description
1 public ServerSocket(int port) throws IOException
Creates a server socket bound to a specific port.
2 public ServerSocket(int port, int backlog) throws IOException
Creates a server socket with the specified backlog and binds it to the specified local port number.
3 public ServerSocket(int port, int backlog, InetAddress address) throws IOException
Creates a server using the specified port, listen backlog, and local IP address to bind to.
4 public ServerSocket() throws IOException
Creates an unbound server socket.

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

Here are some common methods of the ServerSocket class:

No. Method Description
1 public int getLocalPort()
Returns the port on which this socket is listening.
2 public Socket accept() throws IOException
Listens for and accepts connections to this socket.
3 public void setSoTimeout(int timeout)
Enables/disables SO_TIMEOUT with the specified timeout value, in milliseconds.
4 public void bind(SocketAddress host, int backlog)
Binds the ServerSocket to a specific address (IP address and port number).

Socket Class Methods

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 by instantiating one, while the server obtains a Socket object through the return value of the accept() method.

The Socket class has five constructors.

No. Method Description
1 public Socket(String host, int port) throws UnknownHostException, IOException.
Creates a stream socket and connects it to the specified port number on the specified host.
2 public Socket(InetAddress host, int port) throws IOException
Creates a stream socket and connects it to the specified port number on the specified IP address.
3 public 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.
4 public 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.
5 public Socket()
Creates an unconnected socket using the system-default type of SocketImpl.

When the Socket constructor returns, it does not simply instantiate a Socket object; it actually attempts to connect to the specified server and port.

Some methods of interest 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.

No. Method Description
1 public void connect(SocketAddress host, int timeout) throws IOException
Connects this socket to the server and specifies a timeout value.
2 public InetAddress getInetAddress()
Returns the address to which this socket is connected.
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 to which this socket is connected, or null if it is not connected.
6 public InputStream getInputStream() throws IOException
Returns the input stream of this socket.
7 public OutputStream getOutputStream() throws IOException
Returns the output stream of this socket.
8 public void close() throws IOException
Closes this socket.

InetAddress Class Methods

This class represents an Internet Protocol (IP) address. The following lists some useful methods for Socket programming:

No. Method Description
1 static InetAddress getByAddress(byte[] addr)
Returns an InetAddress object given the raw IP address.
2 static InetAddress getByAddress(String host, byte[] addr)
Creates an InetAddress based on the provided hostname and IP address.
3 static InetAddress getByName(String host)
Determines the IP address of a host given the hostname.
4 String getHostAddress() 
Returns the IP address string (in textual form).
5 String getHostName() 
Gets the hostname for this IP address.
6 static InetAddress getLocalHost()
Returns the local host.
7 String toString()
Converts this IP address to a String.

Socket Client Example

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

GreetingClient.java file code:

//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("Connecting 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 Example

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

GreetingServer.java file code:

//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 to 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 run the following commands to start the service using port number 6066:

$ javac GreetingServer.java 
$ java GreetingServer 6066
等待远程连接,端口号为:6066...

Open a new command window and execute the above command to start the client:

$ javac GreetingClient.java 
$ java GreetingClient localhost 6066
连接到主机:localhost ,端口号:6066
远程主机地址:localhost/127.0.0.1:6066
服务器响应: 谢谢连接我:/127.0.0.1:6066
Goodbye!
Other extensions