Java Tutorial

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java List Interface

Java Queue Interface

Java Map Interface

Java Set Interface

Java Data Structures

Java Collections Algorithms

Java Miscellaneous

Advanced Java

Java APIs & Frameworks

Java Useful Resources

Java - Socket Programming

Socket Programming in Java

Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.

When the connection is made, the server creates a socket object on its end of the communication. The client and the server can now communicate by writing to and reading from the socket.

The class represents a socket, and the class provides a mechanism for the server program to listen for clients and establish connections with them.

Steps of Socket Programming in Java

The following steps occur when establishing a TCP connection between two computers using sockets −

  • The server instantiates a ServerSocket object, denoting which port number communication is to occur on.

  • The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port.

  • After the server is waiting, a client instantiates a Socket object, specifying the server name and the port number to connect to.

  • The constructor of the Socket class attempts to connect the client to the specified server and the port number. If communication is established, the client now has a Socket object capable of communicating with the server.

  • On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket.

After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream. TCP is a two-way communication protocol, hence data can be sent across both streams at the same time.

Advantages of Java Socket Programming

  • Platform Independence − One of the biggest advantages of Java Sockets is that they are platform-independent. This means that the same Java code can be run on multiple operating systems and devices without the need for modification. This allows for easy deployment of network-based applications across different systems and ensures that the application can be run on different devices without the need for platform-specific code.

  • Easy to Use − Java Sockets are also relatively easy to use, even for developers who are new to network programming. The Java API provides a simple, consistent interface for creating and managing sockets, which makes it easy to implement network-based applications without needing to understand the underlying network protocols.

  • Scalability − Java Sockets are highly scalable, making them suitable for large-scale network-based applications. They can easily handle thousands of simultaneous connections and can be used to create distributed systems that can handle high levels of traffic.

  • Security − Java Sockets provide built-in support for secure communication, including SSL and TLS encryption. This makes it easy to create secure network-based applications and ensures that sensitive data is protected while in transit.

  • Multithreading − Java Sockets support multithreading, which means that multiple threads can be used to handle multiple connections simultaneously. This improves the performance of network-based applications and allows them to handle a large number of requests without becoming overloaded.

Disadvantages of Java Socket Programming

  • Complexity − While Java Sockets are relatively easy to use, they can still be complex to implement, particularly for developers who are new to network programming. This complexity can make it difficult to debug and troubleshoot network-based applications, which can be time-consuming and frustrating.

  • Latency − Java Sockets can introduce latency into network-based applications, particularly when dealing with large amounts of data. This can be a problem for applications that require real-time communication, such as online gaming or video conferencing.

  • Resource Intensive − Java Sockets can be resource-intensive, particularly when dealing with large numbers of connections or large amounts of data. This can be a problem for systems with limited resources, such as mobile devices or embedded systems.

  • Limited Protocol Support − Java Sockets support a limited number of network protocols, which can be a limitation for certain types of network-based applications. This can make it difficult to create applications that need to communicate with other systems using proprietary protocols.

  • Potential for Security Vulnerabilities − Java Sockets, like any network-based application, are vulnerable to security threats, such as hacking and man-in-the-middle attacks. Careful attention must be paid to security when designing and implementing Java Socket-based systems to ensure that sensitive data is protected and potential vulnerabilities are identified and addressed.

Socket Programming Applications

  • Chat Applications − Java Sockets are often used to create chat applications, such as instant messaging programs and online chat rooms. These types of applications typically use a client-server architecture, where clients connect to a central server to send and receive messages.

  • File Transfer Applications − Java Sockets can also be used to create file transfer applications, such as peer-to-peer file sharing programs. These types of applications use a peer-to-peer architecture, where each device acts as both a client and a server. This allows for direct communication between devices, which can improve the speed and reliability of file transfers.

  • Remote Control Applications − Java Sockets can also be used to create remote control applications, such as remote desktop software. These types of applications use a client-server architecture, where a client connects to a remote server to control the desktop of the server. This allows users to access and control their desktop from any device with an internet connection.

  • Multiplayer Games − Java Sockets are also commonly used to create multiplayer games, such as online role-playing games and first-person shooters. These types of applications typically use a client-server architecture, where clients connect to a central server to play the game. The server acts as the intermediary between clients, handling communication and game logic.

  • IoT Applications − Java Sockets can also be used in IoT (Internet of Things) applications, such as smart home systems. These types of applications use a client-server architecture, where IoT devices connect to a central server to send and receive data. This allows for remote monitoring and control of the devices, as well as data collection and analysis.

Socket Programming Example

Example: Socket Client

The following GreetingClient is a client program that connects to a server by using a socket and sends a greeting, and then waits for a response.

// File Name

public class GreetingClient {

   public static void main(String [] args) {
      String serverName = args[0];
      int port = Integer.parseInt(args[1]);
      try {
         System.out.println("Connecting to " + serverName + " on port " + port);
         Socket client = new Socket(serverName, port);
         System.out.println("Just connected to " + client.getRemoteSocketAddress());
         OutputStream outToServer = client.getOutputStream();
         DataOutputStream out = new DataOutputStream(outToServer);
         out.writeUTF("Hello from " + client.getLocalSocketAddress());
         InputStream inFromServer = client.getInputStream();
         DataInputStream in = new DataInputStream(inFromServer);
         System.out.println("Server says " + in.readUTF());
      } catch (IOException e) {

Example: Socket Server

The following GreetingServer program is an example of a server application that uses the Socket class to listen for clients on a port number specified by a command-line argument −

// File Name

public class GreetingServer extends Thread {
   private ServerSocket serverSocket;
   public GreetingServer(int port) throws IOException {
      serverSocket = new ServerSocket(port);

   public void run() {
      while(true) {
         try {
            System.out.println("Waiting for client on port " + 
               serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            System.out.println("Just connected to " + server.getRemoteSocketAddress());
            DataInputStream in = new DataInputStream(server.getInputStream());
            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
               + "\nGoodbye!");
         } catch (SocketTimeoutException s) {
            System.out.println("Socket timed out!");
         } catch (IOException e) {
   public static void main(String [] args) {
      int port = Integer.parseInt(args[0]);
      try {
         Thread t = new GreetingServer(port);
      } catch (IOException e) {

Compile the client and the server and then start the server as follows −

$ java GreetingServer 6066
Waiting for client on port 6066...

Check the client program as follows −


$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/
Server says Thank you for connecting to /