// Tutorial //

Java Socket Programming - Socket Server, Client example

Published on August 3, 2022
Default avatar
By Pankaj
Developer and author at DigitalOcean.
Java Socket Programming - Socket Server, Client example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Welcome to Java Socket programming example. Every server is a program that runs on a specific system and listens on a specific port. Sockets are bound to the port numbers and when we run any server it just listens on the socket and waits for client requests. For example, tomcat server running on port 8080 waits for client requests and once it gets any client request, it responds to them.

Java Socket Programming

java socket, java socket programming, java socket example A socket is one endpoint of a two-way communication link between two programs running on the network. The socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. In java socket programming example tutorial, we will learn how to write java socket server and java socket client program. We will also learn how server client program read and write data on the socket. java.net.Socket and java.net.ServerSocket are the java classes that implements Socket and Socket server.

Java Socket Server Example

package com.journaldev.socket;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * This class implements java Socket server
 * @author pankaj
 *
 */
public class SocketServerExample {
    
    //static ServerSocket variable
    private static ServerSocket server;
    //socket server port on which it will listen
    private static int port = 9876;
    
    public static void main(String args[]) throws IOException, ClassNotFoundException{
        //create the socket server object
        server = new ServerSocket(port);
        //keep listens indefinitely until receives 'exit' call or program terminates
        while(true){
            System.out.println("Waiting for the client request");
            //creating socket and waiting for client connection
            Socket socket = server.accept();
            //read from socket to ObjectInputStream object
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            //convert ObjectInputStream object to String
            String message = (String) ois.readObject();
            System.out.println("Message Received: " + message);
            //create ObjectOutputStream object
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            //write object to Socket
            oos.writeObject("Hi Client "+message);
            //close resources
            ois.close();
            oos.close();
            socket.close();
            //terminate the server if client sends exit request
            if(message.equalsIgnoreCase("exit")) break;
        }
        System.out.println("Shutting down Socket server!!");
        //close the ServerSocket object
        server.close();
    }
    
}

Java Socket Client

package com.journaldev.socket;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * This class implements java socket client
 * @author pankaj
 *
 */
public class SocketClientExample {

    public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException{
        //get the localhost IP address, if server is running on some other IP, you need to use that
        InetAddress host = InetAddress.getLocalHost();
        Socket socket = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        for(int i=0; i<5;i++){
            //establish socket connection to server
            socket = new Socket(host.getHostName(), 9876);
            //write to socket using ObjectOutputStream
            oos = new ObjectOutputStream(socket.getOutputStream());
            System.out.println("Sending request to Socket Server");
            if(i==4)oos.writeObject("exit");
            else oos.writeObject(""+i);
            //read the server response message
            ois = new ObjectInputStream(socket.getInputStream());
            String message = (String) ois.readObject();
            System.out.println("Message: " + message);
            //close resources
            ois.close();
            oos.close();
            Thread.sleep(100);
        }
    }
}

To test java socket programming of server-client communication, first we need to run SocketServerExample class. When you will run socket server, it will just print “Waiting for client request” and then wait for the client request. Now when you will run SocketClientExample class, it will send a request to java socket server and print the response message to console. Here is the output of java socket server SocketServerExample program.

Waiting for the client request
Message Received: 0
Waiting for the client request
Message Received: 1
Waiting for the client request
Message Received: 2
Waiting for the client request
Message Received: 3
Waiting for the client request
Message Received: exit
Shutting down Socket server!!

Here is the output of Java socket client SocketClientExample program.

Sending request to Socket Server
Message: Hi Client 0
Sending request to Socket Server
Message: Hi Client 1
Sending request to Socket Server
Message: Hi Client 2
Sending request to Socket Server
Message: Hi Client 3
Sending request to Socket Server
Message: Hi Client exit

That’s all for a quick roundup of Socket programming in java. I hope you can get started with java socket server and java socket client programming. Reference: Oracle Doc

If you’ve enjoyed this tutorial and our broader community, consider checking out our DigitalOcean products which can also help you achieve your development goals.

Learn more here


About the authors
Default avatar
Pankaj

author

Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?

Pankaj, I have to write a client program that will connect using socket TCP IP to a third party component. As per manual of component it says 1) responce to my command will be sent to consuming client and later another response will come post successful internal operation. Can you guide how to read the response on socket if multiple response to single request is coming . Please note there may be slight delay in receiving 2nd response .

- Abhishek

    Create a client server application (using socket) in java. Details of Client and server are as follows: Server: You are given a text file. Read the text file on server side.(It contains comma separated data) The data is of following format(Citizen’s data) ID Passport No / CNIC Name Father Name DOB UserName Password Citizen OR Non-Citizen Read the data line by line. Tokenize it and create object of citizens. A citizen class contains following attributes:  Id  Passport no  Name  Father name  Date Of birth  User Name  Password  Type (an int value if 1 the citizen if 2 then non-citizen)  Income tax percentage. Client: Client receives those objects in form of collection or one by one. It calculates income tax percentage on the bases of age. If age is less then 30 then tax will be 7% If age is between 40 and 50 tax will be 5% If age is between 50 and 60 tax will be 3% If it is higher then 60 No tax applicable. After assigning the value of tax send the data back to server and print those on server.

    - osama akbar

      How do we write some text in server side for it to appear on client side with a carriage return each time for changing the Input & vice versa using datagrams Plzz Help

      - Hareesh

        how can I run the program in command

        - nour razin

          This one works unlike the others you see some places. Great job Sir.

          - myname

            Hello ^^ Thank you so much for your tutorial. I have a question though. I have been struggling with implementing the logic you implemented with a JavaEE web application (using war packaging). Do you have any idea how I can implement it ?

            - Rachel

              sir how to connect server remotely.which ip address should i put in “Socket s=new Socket(“localhost”,4103)” replacement of localhost.

              - sumit

                Do the server and client have to be run on the same computer?

                - Kevin Ziadeh

                  I have a TCP server setup which is receiving data from GPS Trackers. Each GPS devices initiates the request, server accepts it. Works well. Now, I want to use TCP to send commands to devices over GPRS for all kinds of configuration. what is the solution and how to do it in using JAVA? I also have the protocol manual where I can see available commands and their responses. example command for locating: server -> device **,imei:359586018966098,100 device -> server imei:353451044508750,001,0809231929,F,055403.000,A,2233.1870,N,11354.3067,E,0.00,; How can I send this command with JAVA ?

                  - Md. Abdul Owares

                    Well explained. Thanks

                    - Douglas