Java Socket Programming: Enabling Communication Between Applications

Learn about Java Socket programming, a technique used for communication between applications running on different Java Runtime Environments (JREs). Discover how socket programming supports both connection-oriented and connection-less communication methods in Java.



Java Socket Programming

Java Socket programming is used for communication between applications running on different JREs. It can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming, while DatagramSocket and DatagramPacket classes are used for connection-less socket programming.

Client Requirements

The client in socket programming must know:

  • IP Address of the Server
  • Port number

We will create a one-way client and server communication where the client sends a message to the server, and the server reads and prints it. Two classes are used: Socket and ServerSocket. The Socket class is used for communication between the client and server, while the ServerSocket class is used at the server side. The accept() method of ServerSocket blocks the console until the client connects. After a successful connection, it returns an instance of Socket at the server side.

Socket Programming in Java

Socket Class

A socket is an endpoint for communication between machines. The Socket class can be used to create a socket.

Important Methods

Method Description
public InputStream getInputStream() Returns the InputStream attached to this socket.
public OutputStream getOutputStream() Returns the OutputStream attached to this socket.
public synchronized void close() Closes this socket.

ServerSocket Class

The ServerSocket class can be used to create a server socket. This object is used to establish communication with clients.

Important Methods

Method Description
public Socket accept() Returns the socket and establishes a connection between the server and client.
public synchronized void close() Closes the server socket.

Example of Java Socket Programming

Creating Server:

To create the server application, we need to create an instance of ServerSocket class. Here, we use port number 6666 for communication between the client and server. The accept() method waits for the client. If a client connects with the given port number, it returns an instance of Socket.

ServerSocket ss = new ServerSocket(6666);
Socket s = ss.accept(); // Establishes connection and waits for the client

Creating Client:

To create the client application, we need to create an instance of the Socket class. Here, we pass the IP address or hostname of the Server and a port number. We use "localhost" because our server is running on the same system.

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

Here is a simple example of Java socket programming where the client sends a text and the server receives and prints it.

Syntax

import java.net.*;

public class MyServer {
    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(6666);
            Socket s = ss.accept(); // Establishes connection
            DataInputStream dis = new DataInputStream(s.getInputStream());
            String str = (String) dis.readUTF();
            System.out.println("message= " + str);
            ss.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

File: MyClient.java

Syntax

import java.net.*;

public class MyClient {
    public static void main(String[] args) {
        try {
            Socket s = new Socket("localhost", 6666);
            DataOutputStream dout = new DataOutputStream(s.getOutputStream());
            dout.writeUTF("Hello Server");
            dout.flush();
            dout.close();
            s.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

To execute this program, open two command prompts and execute each program in each command prompt as shown below. After running the client application, a message will be displayed on the server console.

Example of Java Socket Programming (Read-Write Both Sides)

In this example, the client writes first to the server, then the server receives and prints the text. The server then writes to the client, and the client receives and prints the text. This process continues until "stop" is sent.

File: MyServer.java

Syntax

import java.net.*;
import java.io.*;

class MyServer {
    public static void main(String args[]) throws Exception {
        ServerSocket ss = new ServerSocket(3333);
        Socket s = ss.accept();
        DataInputStream din = new DataInputStream(s.getInputStream());
        DataOutputStream dout = new DataOutputStream(s.getOutputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String str = "", str2 = "";
        while (!str.equals("stop")) {
            str = din.readUTF();
            System.out.println("client says: " + str);
            str2 = br.readLine();
            dout.writeUTF(str2);
            dout.flush();
        }
        din.close();
        s.close();
        ss.close();
    }
}

File: MyClient.java

Syntax

import java.net.*;
import java.io.*;

class MyClient {
    public static void main(String args[]) throws Exception {
        Socket s = new Socket("localhost", 3333);
        DataInputStream din = new DataInputStream(s.getInputStream());
        DataOutputStream dout = new DataOutputStream(s.getOutputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String str = "", str2 = "";
        while (!str.equals("stop")) {
            str = br.readLine();
            dout.writeUTF(str);
            dout.flush();
            str2 = din.readUTF();
            System.out.println("Server says: " + str2);
        }
        dout.close();
        s.close();
    }
}