How to perform socket programming in Java

TCP sockets

Java provides two classes to implement connection-oriented communication. These are:

  • ServerSocket: server side of the socket
  • Socket: client side of the socket

ServerSocket

An object of the server socket can be made when the port number on which to bind is provided. This socket has an accept() method that blocks until a connection request is made from a client. The return value of this function is a Socket object.

Socket

The constructor takes a hostname and port number to which the request for connection is sent.

Some important methods of the Socket class are as follows:

  • public InputStream getInputStream() : returns the InputStream of the socket
  • public OutputStream getOutputStream() : returns the OutputStream of the socket

Code

An example of a simple TCP server-client application is given below.

1. Server

class Server {
public static void main( String args[] ) {
ServerSocket server = new ServerSocket(8080);
while (true){
Socket clientSocket = server.accept();
BufferedReader inFromClient = inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter outToClient = new PrintWriter(clientSocket.getOutputStream(), true);
String line = inFromClient.readLine();
outToClient.println(line);
inFromClient.close();
outToClient.close();
clientSocket.close();
}
}
}

2. Client

class Client {
public static void main( String args[] ) {
Socket socket = new Socket("hostname", 8080);
PrintWriter outToServer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
outToServer.println("Hello World");
String echoedLine = inFromServer.readLine();
inFromServer.close();
outToServer.close();
socket.close();
}
}

Free Resources