Example of How to Create a TCP/IP Server Socket and Client Socket in Java

In this example, Java isĀ used to create a new TCP/IP based server and client socket application. Here, Java SE 8 and the setup in the post below was used. If needed, read it first to setup your Java IDE with Eclipse..

The Java APIs for socket programming are part of the Java SE (Standard Edition). See java.io and java.net.

Summary

  1. Implementation of Server Socket in Java
  2. Implementation of Client Socket in Java
  3. Running the Server Socket and Client Socket
  4. Monitoring TCP/IP Network Traffic using Wireshark

  • Below is the Java source code for the server socket implementation.
  • The server socket is created in line 14. See java.net.ServerSocket for more information.
package com.pgx.java.socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServerSocket {

    private ServerSocket server;

    public MyServerSocket(String bindAddr) throws Exception {
        this.server = new ServerSocket(0, 1, InetAddress.getByName(bindAddr));
    }

    private void listen() throws Exception {
        String data = null;
        Socket client = this.server.accept();
        String clientAddress = client.getInetAddress().getHostAddress();
        System.out.println("\r\nNew connection from " + clientAddress);
        
        BufferedReader in = new BufferedReader(
                new InputStreamReader(client.getInputStream()));        

        while ( (data = in.readLine()) != null ) {
            System.out.println("\r\nMessage from " + clientAddress + ": " + data);
        }
    }

    public InetAddress getSocketAddress() {
        return this.server.getInetAddress();
    }
    
    public int getPort() {
        return this.server.getLocalPort();
    }

    public static void main(String[] args) throws Exception {
        MyServerSocket app = new MyServerSocket(args[0]);
        
        System.out.println("\r\nRunning Server: " + 
                "Host=" + app.getSocketAddress().getHostAddress() + 
                " Port=" + app.getPort());
        
        app.listen();
    }
}

The main methods in this class:

  • Requires one input argument, the host name to use.
  • This can be an IP address or a host name string.
  • The port to listen on will be automatically selected.

  • Below is the Java source code for the client socket implementation.
  • The server socket is created in line 15. See java.net.Socket for more information.
package com.pgx.java.socket;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class MyClientSocket {

    private Socket socket;
    private Scanner scanner;

    private MyClientSocket(InetAddress serverAddress, int serverPort) throws Exception {
        this.socket = new Socket(serverAddress, serverPort);
        this.scanner = new Scanner(System.in);
    }

    public static void main(String[] args) throws Exception {                       
        MyClientSocket client = new MyClientSocket(
                InetAddress.getByName(args[0]), 
                Integer.parseInt(args[1]));
        
        System.out.println("\r\nConnected to: " + client.socket.getInetAddress());
        client.start();             
    }

    private void start() throws IOException {
        String input;

        while (true) {
            input = scanner.nextLine();

            PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true);
            out.println(input);
            out.flush();
        }
    }   
}

  • Here, the application was exported to an executable JAR file named TCPSocketTest.jar.
  • The server- and client socket will be run on the same machine with IP address 192.168.0.15.

3.1 Start the Server

  • To run the server socket from a terminal or Windows command prompt, use the java command:
  java -cp TCPSocketTest.jar com.pgx.java.socket.MyServerSocket 192.168.0.15
  • Where the first input argument is the server name or IP address, here 192.168.0.15.
  • When the server socket is running, it will print the host name and the socket port.

MyMac:Java root$ ls
TCPSocketTest.jar
MyMac:Java root$ java -cp TCPSocketTest.jar com.pgx.java.socket.MyServerSocket 192.168.0.15

Running Server: Host=192.168.0.15 Port=53257
 
  • The socket port, here 53257, is set automatically. See line 14 in the MyServerSocket code and java.net.ServerSocket for more information.
  • The server socket is now ready to accept client connections.

3.2 Start the Client

  • To run the client socket from a terminal or Windows command prompt, use the java command:
  java -cp TCPSocketTest.jar com.pgx.java.socket.MyClientSocket 192.168.0.15 53257

MyMac:Java root$ ls
TCPSocketTest.jar
MyMac:Java root$ java -cp TCPSocketTest.jar com.pgx.java.socket.MyClientSocket 192.168.0.15 53257

Connected to: /192.168.0.15
 
  • The server socket application will print a message indicating that a client connection was established.

3.3 Send a Message

  • In the client socket application, type a message and press ENTER.

MyMac:Java root$ ls
TCPSocketTest.jar
MyMac:Java root$ java -cp TCPSocketTest.jar com.pgx.java.socket.MyClientSocket 192.168.0.15 53257

Connected to: /192.168.0.15
Hello from the client!

  • The server socket application, will print the message that was received from the client.

MyMac:Java root$ ls
TCPSocketTest.jar
MyMac:Java root$ java -cp TCPSocketTest.jar com.pgx.java.socket.MyServerSocket 192.168.0.15

Running Server: Host=192.168.0.15 Port=53257

Message from 192.168.0.15: Hello from the client!
 
  • The Java server and client applications can be stopped by pressing CTRL + C.

Wireshark - Download Website

  • After installation, run Wireshark and select a network interface to capture traffic on.
  • Here, the localhost’s Loopback interface lo0 is selected to monitor local traffic.

Wireshark - Select Network Interface for Network Traffic Capture

  • In the green filter field, enter the below pattern to filter the traffic by the server socket TCP port:
tcp.port == 53257
  • Send messages from the client- to the server socket to capture traffic.
  • To view the payload of a TCP packet, expand the Data node and click on the [Length: ..] item.

Wireshark - TCP Traffic Capture on Loopback Interface