In this article, we are going to learn about socket programming in java. Most computer science graduates are familiar with the concepts of computer networking and its applications. One of the subdomains in computer networking is socket programming. Socket programming is a way of establishing a connection between two different nodes in a network where one node sends the data and the other one receives the data. In computer networking these connections can be established using two ways, connection-oriented (also known as TCP/IP protocol) and connectionless protocol(also known as UDP protocol). 

Full Stack Java Developer Course

In Partnership with HIRIST and HackerEarthEXPLORE COURSE
Full Stack Java Developer Course

What Is a Socket in Java?

In the Java programming language, a socket is defined as an endpoint of a communication link that is established between two nodes or two machines in a network. It has an IP address and port number assigned to it. In Java programming, one can make use of the Socket class and its inbuilt methods to create and maintain a socket in the network. There are two different types of sockets present in socket programming, known as server socket and client socket. The socket present at the client end is called the client socket and on the side of the server is called the server socket. Initially, as mentioned above, the programmer needs to create two sockets and assign them the IP address along with the port number. As next steps, care needs to be taken of the client-side programming and the server-side programming.

Client-Side Programming

The term client-side programming refers to all the programming done under the client-side of the communication link. The main principle behind the client-server communication is that firstly, the client waits for the server to start and then sends a request to the server via the connection formed between corresponding sockets. Then the client waits for the response from the server side.  Let us take a deep dive into the concepts of client-side programming.

Establish a Socket Connection

To enable communication between two machines there must be sockets present at both endpoints. Using the socket class in java, one can create sockets. Another important thing is that the client must know the IP address of the machine on which the server is present.  One can create a socket with a single line of code:

Socket clientSocket = new Socket(“127.0.0.1”, 4000)

where clientSocket represents the socket present at the client end, the number 4000 represents the TCP port number, and 127.0.0.1 represents the IP address of the machine on which the server is running. The above line of Java code, helps the programmer to create a socket at the client end when the server has accepted the connection, else an exception will be thrown. 

Communication

After the successful creation of sockets, to enable communication between them, programmers make use of the data streams. There are two types of data streams in networking, known as the Input stream and the Output Stream. The input stream of the server is connected to the output stream of the client, whereas the input stream of the client is connected to the output stream of the server.

FREE Java Certification Training

Learn A-Z of Java like never beforeEnroll Now
FREE Java Certification Training

Closing the Connection

Finally, once the purpose is fulfilled the programmer needs to close the connection established earlier.

Java Implementation

Let us have a look at the Java implementation of client-side programming.

// A Java program for a ClientSide

import java.net.*;

import java.io.*;

public class ClientProgram

{

// initialize socket and input output streams

private Socket socket = null;

private DataInputStream input = null;

private DataOutputStream out = null;

// constructor to put ip address and port

public Client(String address, int port)

{

// establish a connection

try

{

socket = new Socket(address, port);

System.out.println("Connected");

// takes input from terminal

input = new DataInputStream(System.in);

// sends output to the socket

out = new DataOutputStream(socket.getOutputStream());

}

catch(UnknownHostException u)

{

System.out.println(u);

}

catch(IOException i)

{

System.out.println(i);

}// string to read message from input

String line = "";

// keep reading until "Over" is input

while (!line.equals("Over"))

{

try

{

line = input.readLine();

out.writeUTF(line);

}

catch(IOException i)

{

System.out.println(i);

}

}

// close the connection

try

{

input.close();

out.close();

socket.close();

}

catch(IOException i)

{

System.out.println(i);

}

}

public static void main(String args[]) {

Client client = new Client("127.0.0.1", 4000);

}

}

Server Programming

On the other hand, similar to the client-side programming there is server-side programming which basically deals with stuff related to programming at the server end. Typically, the server runs on a machine that is present over a network and bound to a particular port number. In the above topic, client-side programming we considered 4000 as our port number. Let us take a deep dive into the concepts of client-side programming.

Establish a Socket Connection

We are aware of the fact that to enable communication between two machines there must be sockets present at both endpoints. Using the Socket class in java, one can create a socket with a single line of code:

ServerSocket serverSocket = new ServerSocket(4000);

Where the argument 4000 is our port number and the server waits for a connection request from the client side at the server socket. Once a connection request is received then the below line of code gets executed.

Socket clientSocket = serverSocket.accept();

This means that if the protocol is maintained and followed properly, then the request would be accepted by the server. 

Caltech Coding Bootcamp

Become a full stack developer in 6 monthsEnroll Now
Caltech Coding Bootcamp

Communication

Once the connection is accepted, a new socket along with the client socket will be assigned to the server with the same port number 4000. Thus the new socket object maintains direct communication with the client. Hence one can write and read the messages to and fro from server to client. This connection enables the continual transfer of data between the client and server. 

Close the Connection

Finally, once the purpose is fulfilled the client sends a request to the server to terminate the connection between the client socket and server socket. 

Important Points 

Let us understand some of the important points in socket programming.

  1. When a socket is created at the server end, a random port number will be assigned to it. In our example, it is 4000 which means that the server socket listens to the requests from the clients coming in from port 4000.
  2. Then a client sends a request to the server end by taking two parameters such as the IP address and the port number. 
  3. Once a server gets a proper request (all protocols should be followed) from the client, then it accepts it using accept() call.
  4. Using various methods present in the java.net.Socket class we can send and receive data across the network between server and client.
  5. Once the purpose of establishing the connection is fulfilled, then close the connection between the sockets.
  6. To run the program, initially run the server program and then run the client program. 

To run on Terminal or Command Prompt

The Java codes for both the client-side and the server-side are saved in a file with the .java extension. These codes can be made to run on the terminal (in UNIX-based systems) or in the command prompt (in Windows systems). There are certain steps to be followed while running the programs via terminal or command prompt.

  1. Initially open the command prompt or terminal. 
  2. Change your path to the directory that contains the java files of the server and client.
  3. Now run the server program using the command - $ java server.
  4. So, now the server has started its execution and is ready to accept the connections from the client. 
  5. Start running the client program in the terminal using the command - $ java client.
  6. It will display a few lines of text that the client sent its request to the server and the server accepted the connection.
  7. The entire situation will be demonstrated below:

Server: Server Started, successfully!! And waiting for the connections to 

come in

Client: The client started, successfully!! And ready to send requests to 

the Server. (sends a connection request to the server)

Server: Successfully, accepted the client's request.

Client: Successfully, connected to the server. And sends a message to the server as HI and over”

This message is shown at the server end as well

Server: HI and over

By sending the word ‘over’ the connection is closed. 

Socket Class

Basically, a socket and socket class are the most important things in a connection-oriented protocol. The socket class consists of all required input parameters and the methods which help the programmers from the creation of sockets to data transfer between the sockets. It also enables both synchronous and asynchronous transfer of data between the ends.

Important Methods

Here is a list of important methods that are present in the Socket Class:

  1. gePort()
  2. getInputStream()
  3. getOutputStream()
  4. getLocalPort()
  5. bind()
  6. close()
  7. isClosed()
  8. isConnected() and so on

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

ServerSocket Class

Another important class in socket programming is ServerSocket class. This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the client.

Important Methods

Here is a list of important methods that are present in the Socket Class:

  1. accept()
  2. bind()
  3. close()
  4. channel()
  5. isBound()
  6. isClosed() and so on

What Is TCP?

The term TCP stands for Transmission Control Protocol. It is also known as a connection-oriented protocol. It is one of the most widely used protocols used in the IP suite. It enables the computer machines to establish connections between them across the network and transfer the data packets. Error detection, and reliable communication are some of its features.

Two categories of Sockets

We have seen earlier that there are two types of sockets in computer networking. They are client socket and server socket. A server socket waits for a request from a client, whereas a client socket helps in establishing communication between the client and the server.

Creating a Socket Connection

Socket plays a major role in computer networking concepts. These are considered to be the endpoints for a communication line. In order to establish a connection between two machines firstly, two sockets have to be created at both the server and client end. The server end socket is taken care of by the ServerCocket class and the client end socket is taken care of by the Server class in Java programming language. The client has the necessity to get to know the details of the IP address and the port number in order to connect to the server.

The client sends a request and waits till it gets accepted at the server's end. The request is accepted at the server’s end by using the accept() method. Once the connection is found to be successful, data can be transferred from one node to another node present on the network. 

Example of Java Socket Programming

Programming the Server-Side Application

Using a single line of java code, a server end socket can be created.

ServerSocket serverSocket = new ServerSocket(4000);

Where the argument 4000 is our port number and the server waits for a connection request from the client side at the server socket. Once a connection request is received then the below line of code gets executed.

Socket clientSocket = serverSocket.accept();

package com. company; 

import java.io.*;  

import java.net.ServerSocket;  

import java.net.Socket;  

public class Server {  

  public static void main(String[] args) throws IOException {   

      Socket socket ;  

      InputStreamReader inputStreamReader ;  

      OutputStreamWriter outputStreamWriter ;  

      BufferedReader bufferedReader ;  

      BufferedWriter bufferedWriter ;  

      ServerSocket serversocket ;  

      serversocket = new ServerSocket(5000);  

      while (true) {  

          try {    

              socket = serversocket.accept();        

              inputStreamReader = new InputStreamReader(socket.getInputStream());  

              outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());  

              bufferedReader = new BufferedReader(inputStreamReader);  

              bufferedWriter = new BufferedWriter(outputStreamWriter);  

              while (true){  

                  String msgFromClient = bufferedReader.readLine();  

                  System.out.println("Client: " + msgFromClient);   

                  bufferedWriter.write(" MSG Received"); 

                  bufferedWriter.newLine();  

                  bufferedWriter.flush(); 

                  if (msgFromClient.equalsIgnoreCase("BYE"))  

                  break;  

              }  

              socket.close();  

              inputStreamReader.close();  

              outputStreamWriter.close();  

              bufferedReader.close();  

              bufferedWriter.close();  

          } catch (IOException e) {  

              e.printStackTrace();  

          }  

        }  

    }  

}

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

Programming the Client-Side Application

One can create a socket with a single line of code:

Socket clientSocket = new Socket(“127.0.0.1”, 4000)

where clientSocket represents the socket present at the client end, the number 4000 represents the TCP port number, and 127.0.0.1 represents the IP address of the machine on which the server is running.

The client end socket waits for the acceptance of the request from the server’s end. 

package com. company;  

import java.io.*;  

import java.net.Socket;  

import java.util.Scanner;    

public class client {  

    public static void main(String[] args) {  

        Socket socket = null;  

        InputStreamReader inputStreamReader = null;  

        OutputStreamWriter outputStreamWriter = null;  

        BufferedReader bufferedReader = null;  

        BufferedWriter bufferedWriter = null;          

        try {  

            socket = new Socket("localhost", 5000);  

            inputStreamReader = new InputStreamReader(socket.getInputStream());  

            outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());  

            bufferedReader = new BufferedReader(inputStreamReader);  

            bufferedWriter = new BufferedWriter(outputStreamWriter);  

            Scanner scanner = new Scanner(System.in);  

            while (true){  

                String msgToSend = scanner.nextLine();  

                bufferedWriter.write(msgToSend);  

                bufferedWriter.newLine();  

                bufferedWriter.flush();                 

                System.out.println("Server: " + bufferedReader.readLine());  //printing the server message               

                if (msgToSend.equalsIgnoreCase("BYE"))  

                    break;  

            }  

        } catch (IOException e) {  

            e.printStackTrace();  

        } finally {  

             try {  

                  if (socket != null)  

                  socket.close();  

                  if (inputStreamReader != null)  

                    inputStreamReader.close();  

                  if (outputStreamWriter != null)  

                  outputStreamWriter.close();  

                  if (bufferedReader != null)  

                  bufferedReader.close();  

                  if (bufferedWriter != null)  

                  bufferedWriter.close();  

             } catch (IOException e) {  

            e.printStackTrace();  

          }  

       }  

    }  

}

Socket_Java.

Fig: Representation of SOCKET API at client and server ends

Testing the Applications

We can test the server and client end codes using terminal or the command prompt or any other IDEs. Some of the steps are mentioned below:

Using Intellij or Other IDEs

  1. Compile the two programs on the IDE in different windows.
  2. Run the server program first, then the client program.
  3. Type messages in the client window, which will be received and shown by the server window at the same time.
  4. To close the connection enter ‘over’.

Using Command Prompt/Terminal

  1. Create a new folder named ‘PROJECT’.
  2. Put the Server.java and Client.java code files into the project folder.
  3. Open the command prompt and navigate to the path of the directory that contains both the code files.
  4. Run javac PROJECT\Server.java and then run java project.Server.
  5. Run the client program using the same process as the Server code.
  6. You can then type messages in the client window.
  7. If you want to close the connection, the client can send a ‘bye’ message to the server. 
We offer complete Job Guarantee and money-back if you don't secure a job within 6 months of graduation. Get interview ready with intense and comprehensive career mentoring sessions in our Full Stack Java Developer Program. Enroll TODAY!

Conclusion

Hope this article was able to give you a thorough understanding of Socket programming in Java. If you are looking to enhance your skills further, we would recommend you check Simplilearn’s Post Graduate Program in Full Stack Web Development. This course is made in collaboration with Caltech CTME. It can help you hone the relevant software development skills and make you job-ready in just 6 months.

If you have any queries or doubts, feel free to post them in the comments section below. Our team will get back to you at the earliest.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.