Tutorial

Java Socket Programming - Socket Server, Client example

Published on August 3, 2022
author

Pankaj

Java Socket Programming - Socket Server, Client example

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

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

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.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 23, 2013

Hi Pankaj Thanks for this article … I am working on Vehicle tracking system. Device is already implemented in one place and IP and port is integrated with that GPS device . I need to received data from that gps device . If you have any sample work in java , please share with me . Thanks

- Manish

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 13, 2014

Hi Pankaj Thanks for this article … I am working on Vehicle tracking system. Device is already implemented in one place and IP and port is integrated with that GPS device . I need to received data from that gps device . If you have any sample work in java , please share with me . Thanks

- amir

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 22, 2014

    where i put server socket file in real server

    - shinu

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 23, 2014

    You can put anywhere you want, you just need to compile (javac SocketServerExample.java) and then run (java SocketServerExample)

    - Jonathan

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      May 23, 2014

      Thanks for this article, It’s really help you’re awesome Man

      - Jonathan

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 11, 2014

        I am working on Socket & also you had given a good & nice example but i have a problem in implementing it, I have made a server socket and client socket they are working good but when i want to communicate from other client it does not respond to that client. Please help me i am working on it for a month & i am unable to figure this out. Please reply me as soon as possible…

        - KoolMaan

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 11, 2014

        If you can send me program, I can check it out. Without having any insight of the issue, it’s not possible to provide any solution.

        - Pankaj

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        July 2, 2015

        Hai Pankaj… I am new to socket programming…I am working with client server communication…Clients sends a request, server reads that request, and sends a response, lastly client reads the response.I tried to implement with the help of many examples.But the client sends a request successfully, and the server reads it and responses successfully but the client then cannot get the response.Please help me….

        - Saranya

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 17, 2018

        Try to use the UDP protocol. I guess it will help!!!

        - Niraj

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          July 24, 2015

          Hello pankaj, This is Tejaswi.I am doing my thesis and i am responsible for wireless connetivity.I have to use a client-server architectire.For that i am using texas instruments simple link wifi(cc3200 ) and an android.I have to send data using TCP connection.There is list of sensors attached to cc3200 .if a client request for a sensor data it just give an information regarding that data.I don’t have any idea how to structure the data.Could you please help me to find a solution. Thanks in advance… Best regards, Tejaswi

          - Tejaswi

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            July 1, 2015

            Hai Pankaj Thanks for this article… I am working with client server communication…Clients sends a request, server reads that request, and sends a response, lastly client reads the response.I tried to implement with the help of many examples.But the client sends a request successfully, and the server reads it and responses successfully but the client then cannot get the response.Please help me…

            - Saranya

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              October 7, 2015

              i am working on spring integration i try to hit controller from device but it can not send data to controller…how it can do…

              - chetan Pawar

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              January 9, 2020

              working on spring integration i try to hit controller from device but it can not send data to controller I understand your question. Good question. Answer is simple and good also. Here is answer, you hit one more time and check. If still no work, then hit pc on ground. Will work for sure. Worked for me.

              - Nazim Techwala

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                May 21, 2016

                any one tell me … multiclent serverSocket … in java, there is any provision for accessing thread from outside class. thread is one of socket client … ???

                - swap

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                January 6, 2020

                multiclent serverSocket ……… in java, there is any provision for accessing thread from outside class. thread is one of socket client …

                - Any One

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  November 15, 2016

                  hi guys, May you please assist. how can I send an xml message to a server & read the server response.

                  - Manqoba Ledwaba

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    November 25, 2016

                    Hi guys, is anyone can tell me how to pass jforms data to anothor jform through localhost?

                    - Ravindu Saluwadana

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      August 22, 2017

                      Thanks a lot for this detail about socket programming in java. As beginner i was looking for this socket programming guide and information. You have defined it so well as it is so important for making program run. Keep sharing.

                      - pranit patil

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        August 30, 2017

                        thank for this article is very informative but I want more information so please share on the web

                        - nitu

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          April 27, 2018

                          thank you so much but it’s not enough for me

                          - ibtissem

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          July 29, 2018

                          What do you want included to have enough?

                          - sunusi aminu

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          August 8, 2018

                          i want more deep in socket programming so dude .thank you its my opinion.

                          - sajid

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            June 12, 2018

                            how can I test this in the different computer?

                            - avneet

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            July 29, 2018

                            You only need to connect the two computers using either wi-fi or cable.

                            - sunusi aminu

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            June 3, 2019

                            i want to connect two pc on a different location, how can i do this… not by the cable or wifi. but with different location pc.

                            - tushar khatyri

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              January 9, 2019

                              hello good afternoon, I just read your post and I found it quite interesting, but I would like to know this connection that is made a travz of applications java can get to have communication through the internet. is that I am new in this language … is that I am creating a java application that they have to communicate but they are far away and the only way to communicate is through the internet. Can work?

                              - kervin Cortez

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              January 15, 2019

                              good question but no relevant in this context

                              - chutki

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              July 16, 2019

                              yes…of course!!!

                              - diwagar

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                February 20, 2019

                                Great implementation to start working with socket communication. The use of Object(Input/Output)Stream was very appreciated, many thanks for this.

                                - Lucio Jose Beirao

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  May 7, 2019

                                  Hi Pankaj, I was doing socket connection and I have to read character by character. But the read method is never reaching EOF(i.e never getting -1) until I close my connection, But I cannot open and close the connection for multiple records. Is there anyway to solve this? Also while writing data, I am only able to use println method but not write method.

                                  - Kranthi Kumar

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    June 1, 2019

                                    i want that the client starts responding when it gets data from server. How can i do it?

                                    - sumit lohan

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      July 15, 2019

                                      Please do increase(width wise) the content container, it seems weird to read in such a small container, rest all of the space is just lying vacant

                                      - testtr

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        November 29, 2019

                                        Very good! It helps a lot, thank you so much.

                                        - Jeisy

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          December 19, 2019

                                          Hi Pankaj, Thanks for the article. Its running fine on Intranet but I am not able to connect it over internet. Please suggest something.

                                          - Sikander Bhardwaj

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          December 19, 2019

                                          Must be some firewall blocking it and ports are not open.

                                          - Pankaj

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          December 19, 2019

                                          I have disabled the firewall but its not working. I have created a Remote desktop application which overs in fine in my office LAN but I am not able to connect outside LAN. Is it possible for you to connect with me over email so that I can share my code with you. I ll grateful to you if you help me.

                                          - Sikander Bhardwaj

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          January 20, 2020

                                          Hi Sikander how define client messge ex - my client send this $,LGN,MARK,DL20DL2020,358980100027391,V0.0.1,AIS140,28.359961,N,76.927612,E Response should be - $LGN20202020121212* or if client send this $,HBT,MARK,V0.0.1,358980100027391,38,20,0,20,20,0000,0.1,* then response should be - $HBT* please help 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(); } }

                                          - Rudraa Kumar

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            December 26, 2019

                                            hey Pankaj thanku for tutorial but i’ve a queation ( whan destination device storage is full then my app start crashing) how to handle this bug …will be very thankful

                                            - Ch.LE0

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              January 9, 2020

                                              Hi Pankaj, Thanks for this great post, I have a problem with an implementation, I am connecting to a socket and everything was going good until my customer started to complain that he was seeing issues from time to time they provided their logs and it seems like they are receiving the payload message split in two which is obviously causing problems. what could be wrong? this is part of my client implementation: try { socket = new Socket(settings.getApiDepositHost(), settings.getApiDepositPort()); log.debug(“Writing request to the server”); // send the request PrintWriter output = new PrintWriter(socket.getOutputStream(), true); output.print(request); output.flush(); // read the response StringBuffer buffer = new StringBuffer(); InputStreamReader input = new InputStreamReader(socket.getInputStream()); char[] charBuffer = new char[1024]; int read; // keep reading until the buffer is terminated with a tag do { do { read = input.read(charBuffer); if (read > 0) { buffer.append(charBuffer, 0, read); } } while (charBuffer.length == read); responseXml = buffer.toString(); } while (!responseXml.endsWith(“</Tag”)); socket.close(); } catch (UnknownHostException e) { //handle error stuff here } catch (IOException e) { //handle error stuff here } I’ve tried to reproduce this but it has not been possible.

                                              - Rafael Cadenas

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                February 20, 2020

                                                Well explained. Thanks

                                                - Douglas

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  February 29, 2020

                                                  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

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    March 16, 2020

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

                                                    - Kevin Ziadeh

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    March 16, 2020

                                                    No, but if they are on different computers/servers, make sure the ports are open for communication.

                                                    - Pankaj

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    April 10, 2020

                                                    how can the server know if one or more clients are disconnecting?

                                                    - NetW

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      May 17, 2020

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

                                                      - sumit

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        May 17, 2020

                                                        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

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          May 28, 2020

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

                                                          - myname

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            December 30, 2020

                                                            how can I run the program in command

                                                            - nour razin

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              June 24, 2021

                                                              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

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                November 18, 2021

                                                                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

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  February 5, 2022

                                                                  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

                                                                    Try DigitalOcean for free

                                                                    Click below to sign up and get $200 of credit to try our products over 60 days!

                                                                    Sign up

                                                                    Join the Tech Talk
                                                                    Success! Thank you! Please check your email for further details.

                                                                    Please complete your information!

                                                                    Become a contributor for community

                                                                    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                                    DigitalOcean Documentation

                                                                    Full documentation for every DigitalOcean product.

                                                                    Resources for startups and SMBs

                                                                    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                                    Get our newsletter

                                                                    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                                    New accounts only. By submitting your email you agree to our Privacy Policy

                                                                    The developer cloud

                                                                    Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                                    Get started for free

                                                                    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                                    *This promotional offer applies to new accounts only.