Socket programming in Java

There are 2 types of sockets in Java.

  1. ServerSocket – TCP
  2. DatagramSocket – UDP

Communicating over tcp/udp is possible through ServerSocket  class. 

Server socket will do below tasks.

  1. Create a Server Socket using ServerSocket Class
  2. Then call accept() method to wait for connections
  3. Then read and write to sockets i/p & o/p streams

Client socket will do below tasks.

  1. Connect to server using below syntax
  2. Socket client = new Socket(serverName, port);
  3. Then read and write to socket using i/p & o/p streams

Server Socket in Java

Here is the sample Java program which illustrates socket programming.

Here is the server code.

package sockets;

/**
 * Created by ssalunke on 12/04/2016.
 */
import java.net.*;
import java.io.*;

public class Server extends Thread {

    public static void main(String[] args) throws Exception {
        System.out.println("Server Listening on 8888");
        ServerSocket serverSocket = new ServerSocket(8888);
        //server timeout 60 minutes
        serverSocket.setSoTimeout(1000 * 60 * 60);

        //Below method waits until client socket tries to connect
        Socket server = serverSocket.accept();

        //Read from client using input stream
        DataInputStream in = new DataInputStream(server.getInputStream());
        System.out.println(in.readUTF());

        //Write to client using output stream
        DataOutputStream out = new DataOutputStream(server.getOutputStream());
        out.writeUTF("Bye sent by Server");

        //close the connection
        server.close();
    }
}

Here is the client code

package sockets;

import java.net.*;
import java.io.*;

public class Client {
    public static void main(String[] args) throws Exception{

        //try to connect to server - localhost @ port 8888
        Socket client = new Socket("localhost",8888);
        //if server is not listening - You will get Exception
        // java.net.ConnectException: Connection refused: connect

        //write to server using output stream
        DataOutputStream out = new DataOutputStream(client.getOutputStream());
        out.writeUTF("Hello server - How are you sent by Client");

        //read from the server
        DataInputStream in = new DataInputStream(client.getInputStream());
        System.out.println("Data received from the server is -> " + in.readUTF());

        //close the connection
        client.close();
    }
}

Please run the server code first then run client code.
Here is the server output.

Server Listening on 8888
Hello server – How are you sent by Client

Here is the client output.
Data received from the server is -> Bye sent by Server

You may also like...