Java Socket Programming – Socket Server, Client example

Filed Under: Java

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

Comments

  1. testtr says:

    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

  2. sumit lohan says:

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

  3. Kranthi Kumar says:

    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.

  4. Lucio Jose Beirao says:

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

  5. kervin Cortez says:

    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?

    1. chutki says:

      good question but no relevant in this context

      1. diwagar says:

        yes..of course!!!!!!!

  6. avneet says:

    how can I test this in the different computer?

    1. sunusi aminu says:

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

      1. tushar khatyri says:

        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.

  7. ibtissem says:

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

    1. sunusi aminu says:

      What do you want included to have enough?

      1. sajid says:

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

  8. nitu says:

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

  9. pranit patil says:

    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.

  10. Ravindu Saluwadana says:

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

  11. Manqoba Ledwaba says:

    hi guys,

    May you please assist.

    how can I send an xml message to a server & read the server response.

  12. swap says:

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

  13. chetan Pawar says:

    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….

  14. Saranya says:

    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….

  15. KoolMaan says:

    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……..

    1. Pankaj says:

      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.

      1. Saranya says:

        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….

        1. Niraj says:

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

      2. Tejaswi says:

        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

  16. Jonathan says:

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

  17. shinu says:

    where i put server socket file in real server

    1. Jonathan says:

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

  18. Manish says:

    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

    1. amir says:

      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

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages