Network programming refers to writing programs that run on multiple devices (computers), all connected by 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 problem solving rather than communication details.

Support for two common networking protocols is provided in the Java.net package:

  • TCP: TCP stands for Transmission Control Protocol, which ensures reliable communication between two applications. Commonly used for Internet protocols, it is called TCP/IP.
  • UDP:UDP stands for User Datagram Protocol, a connectionless protocol. Packets that provide data to be sent between applications.

This article 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 handling: This is covered in a separate section, but click here to learn more about URL handling in the Java language.

Socket programming

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

When a connection is established, the server creates a Socket object. The client and server 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 establish connections with clients.

The following steps occur when a socket is used to establish a TCP connection between two computers:

  • The server instantiates a ServerSocket object that represents communication through a port on the server.
  • The server invokes the Accept () method of the ServerSocket class, which will wait 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 side to communicate with the server.
  • On the server side, the Accept () method returns a new reference to the socket on the server that connects to the socket on the client.

 

After the connection is established, communication is carried out using I/O streams. Each socket has an output stream and an input stream. The output 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 over two data streams at the same time. The following is a complete set of useful methods that some classes provide to implement Sockets.


The ServerSocket class method

The server application uses the java.net.ServerSocket class to get a port and listen for client requests.

The ServerSocket class has four constructors:

The serial number Methods described
1 public ServerSocket(int port) throws IOExceptionCreate a server socket bound to a specific port.
2 public ServerSocket(int port, int backlog) throws IOExceptionCreate a server socket from the specified backlog and bind it to the specified local port number.
3 public ServerSocket(int port, int backlog, InetAddress address) throws IOExceptionCreate a server with the specified port, listening backlog, and local IP address to bind to.
4 public ServerSocket() throws IOExceptionCreate an unbound server socket.

Create 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 is listening for client requests.

Here are some common methods for the ServerSocket class:

The serial number Methods described
1 public int getLocalPort()Returns the port on which this socket listens.
2 public Socket accept() throws IOExceptionListens for and accepts connections to this socket.
3 public void setSoTimeout(int timeout)Enable/disable SO_TIMEOUT by specifying a timeout value in milliseconds.
4 public void bind(SocketAddress host, int backlog)Bind the ServerSocket to a specific address (IP address and port number).

Socket class method

The java.net.Socket class represents the socket that both clients and servers use to communicate with each other. The client gets a Socket object by instantiating it, and the server gets a Socket object by accepting ().

The Socket class has five constructors.

The serial number Methods described
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 IOExceptionCreates a stream socket and connects it to the specified port number at 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 to the specified remote port at the specified remote address.
5 public Socket()Create a disconnected socket with a SocketImpl of the system default type

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

Some of the methods of interest are listed below, noting that both the client and server side have a Socket object, so both the client and server side can call these methods.

The serial number Methods described
1 public void connect(SocketAddress host, int timeout) throws IOExceptionConnect this socket to the server and specify a timeout 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, or NULL if not connected.
6 public InputStream getInputStream() throws IOExceptionReturns the input stream for this socket.
7 public OutputStream getOutputStream() throws IOExceptionReturns the output stream of this socket.
8 public void close() throws IOExceptionClose this socket.

Method of the InetAddress class

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

The serial number Methods described
1 static InetAddress getByAddress(byte[] addr)Given a raw IP address, returns an InetAddress object.
2 static InetAddress getByAddress(String host, byte[] addr)Create an InetAddress based on the host name and IP address provided.
3 static InetAddress getByName(String host)Determine the IP address of the host given the host name.
4 String getHostAddress()Returns the IP address string (as 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 GreetingClient shown below is a client program that connects to the server via socket, sends a request, and then waits 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(); }}}Copy the code

Socket server instance

The following GreetingServer program is a server-side application that uses sockets to listen on 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(); }}}Copy the code

Compile the Java code above and run the following command to start the service, using port 6066:

$ java GreetingServer 6066
Waiting for client on port 6066...
Copy the code

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!Copy the code