A Guide to Java Sockets

May 09, 2022

In Java, a socket is one end of a two-way communication channel between two network-connected applications. It is used to communicate across programs running on different JREs (Java Runtime Environments).

A socket, in general, is a method of establishing a connection between a client and a server. It might be connection-oriented or non-connection-oriented.

Computers must establish a connection for connection-oriented protocols before transferring data. The only connectionless protocol choice is UDP (User Datagram Protocol).

To further demonstrate sockets, we will use the client/server architecture. The client and server correspond by writing to and reading from the socket interrelation.

new java job roles

A Brief Description Of Socket

A socket is a communication endpoint that connects two devices on a network. It has a port number that the TCP/IP layer can use to identify the receiving application.

A port number and an IP address are frequently included in an endpoint.

About TCP

  • TCP stands for Transmission Control Protocol.
  • The Transmission Control System (TCP) is a widely used data transmission protocol that enables client/server endpoints on a network.

Classification of Sockets

  • A server socket – waits for a request from a client.
  • A client socket – Establishes communication between client and server.

Two communication protocols that can be used for socket programming are User Datagram Protocol (UDP) and Transfer Control Protocol (TCP).

The primary distinction is that UDP is connectionless, so there is no session between the client and the server.

Also Read: Guide to hashCode() in Java

Still, TCP is connection-oriented, which means communication must first be established between the client and the server.

This article provides an overview of Java socket programming over TCP/IP networks and examples of client/server Java systems. Let’s get into it.

How to Create a Socket Connection?

The following steps are used to build a socket connection in Java:

  • While identifying the port number on which our communication will occur, the server creates a ServerSocket object. When an I/O error occurs, exception handling mechanisms are used.
  • The server uses the accept() function to validate an incoming request to the socket.
  • The client then builds a Socket object with a specified server name and port number.
  • The Socket class tries to connect the client to the server using the specified port number.
  • The client and server can then interact via I/O streams if the connection is successful. The client and server socket classes handle the I/O streams.

The OutputStream of the client connects with the InputStream of the server. While the server’s OutputStream communicates with the InputStream of the client.

What is Stream?

A stream is essentially a collection of data that has been ordered. There are two primary sorts of streams:

  • A sequence of characters (usually used with text files).
  • A stream of bytes (used with images).

A character stream is written in human-readable characters, whereas a byte stream is written in machine-readable symbols.

Server Side

A server usually operates on a networked computer and has a socket that is tied to a specific port number. In Java, the package java.net is used for socket programming.

This package contains two classes: The Socket class and the ServerSocket class.


In our scenario, we’ll run the server on the same machine as the client and connect to port 6666:

ServerSocket sSocket = new ServerSocket(int portno);

ServerSocket sSocket = new ServerSocket(6666);

The server waits for a client to request a connection by listening to the socket.


This occurs in the next step:

Socket cSocket = sSocket.accept();


The client must know the hostname or IP address of the computer on which the server is executing, as well as the server’s listening port number.


The client tries to connect with the server on the server’s machine and port to issue a connection request:

Socket cSocket = new Socket("localhost",6666);

Constructing a Socket

To construct a socket, utilize the Socket class.

  • public InputStream getInputStream() – restores the InputStream linked with this socket.
  • public OutputStream getOutputStream() – recurs the OutputStream connected with this socket.
  • public synchronized void close() – terminating the socket

Let’s start with the most fundamental scenarios involving a client and a server. It will be a two-way communication application in which the client will greet the server, and the server will answer.

With the following code, we’ll develop the server program in a class called WelcomeServer.java.

  • The client must provide an output to the server in order to deliver data to the server. To write data to a Socket, we utilize PrintWriter.
  • A BufferedReader is used to receive data from a Socket. The client receives data as an input.
import java.io.*; 
import java.net.*;

  public class WelcomeServer { 
  private ServerSocket sSocket; 
  private Socket cSocket; 
  private PrintWriter out; 
  private BufferedReader in;

public void start(int portno) { 
  sSocket = new ServerSocket(portno); 
  cSocket = sSocket.accept(); 
  out = new PrintWriter(cSocket.getOutputStream(), true); 
  in = new BufferedReader(new InputStreamReader

    String welcoming = in.readLine(); 
    if ("hello server".equals(welcoming)) { 

out.println("hey client"); 
   else { out.println("unrecognised welcoming"); 
 public void close() { 

  public static void main(String[] args) { 
     WelcomeServer server=new WelcomeServer(); 


Now we will create a client called WelcomeClient.java with this code:

  public class WelcomeClient { 
  private Socket cSocket; 
  private PrintWriter out; 
  private BufferedReader in; 

public void startConnection(String ip, int port) { 
 cSocket = new Socket(ip, port); 
 out = new PrintWriter(cSocket.getOutputStream(), true); 
 in = new BufferedReader(new InputStreamReader


  public String transmitMessage(String msg) { 

  String response = in.readLine(); 
return response; 

public void stopConnection() { 


Next, using a unit test, we’ll send a welcome to the server, confirming that the server responds with a greeting:

  public void givenGreetingClient_whenServerRespondsWhenStarted_thenCorrect() { 
   WelcomeClient client = new WelcomeClient(); 

client.startConnection("", 6666); 
  String resp = client.sendMessage("hey server"); 
  assertEquals("hey client", resp); 

Socket programming is only the beginning! Sockets are the essential “things” that enable your computer to communicate over a network.


See Also: Introduction to Java Primitives


Sockets and Java allow us to accomplish a variety of things. It would be best if you had mastered the fundamentals of socket programming in Java by now.

You may experiment with things like developing a chat client or anything similar. You may create additional highly productive apps using sockets and the TCP/IP protocol.

new Java jobs



I am a senior technical project manager in a reputable US based software development company. I have been developing and managing innovative solutions for multinational companies, deployed software and systems. I am responsible for full life cycle development of next-generation software, from initial requirement gathering to design, coding, testing, documentation and implementation. Being in technology I love to write about it.

Candidate signup

Create a free profile and find your next great opportunity.


Employer signup

Sign up and find a perfect match for your team.


How it works

Xperti vets skilled professionals with its unique talent-matching process.


Join our community

Connect and engage with technology enthusiasts.