Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
socket
tcp
communitycreator

How to perform socket programming in Java

Fatima Hasan

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();
        }
    }
}
Server side of the application. It takes an input string from the client and sends the same string back.

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();
    }
}
Client side of the app

RELATED TAGS

java
socket
tcp
communitycreator
RELATED COURSES

View all Courses

Keep Exploring