Building TCP Socket Applications in Java

TCP socket programming enables communication between networked applications using the Socket class. The TCP protocol establishes a client-server architecture where the server and client serve distinct roles with different implementation approaches.

InetAddress Class

The InetAddress class from the java.net package provides methods for working with IP addresses and hostnames. This class requires exception handling since operations may throw UnknownHostException when a host cannot be resolved or network connectivity fails.

The following example demonstrates retrieving the local hostname and IP address:

import java.net.*;

public class NetworkInfo {
    public static void main(String[] args) {
        InetAddress localAddress;
        try {
            localAddress = InetAddress.getLocalHost();
            String hostname = localAddress.getHostName();
            String ipAddress = localAddress.getHostAddress();
            System.out.println("Hostname: " + hostname);
            System.out.println("IP Address: " + ipAddress);
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
        }
    }
}

ServerSocket Class

The ServerSocket class binds to a specific port and listens for incoming client connections. When a connection arrives, the accept() method returns a Socket object for bidirectional communication with that client.

TCP Network Communication

In unidirectional communication scenarios, the client sends messages to the server without expecting responses. The client writes data through its output stream while the server reads incoming data through its input stream.

Server Implementation

The server application creates a ServerSocket on a designated port, listens for client connections, and processes incoming messages:

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

public class TcpServer {
    private BufferedReader inputReader;
    private ServerSocket serverSocket;
    private Socket clientConnection;
    
    public void startServer() {
        try {
            serverSocket = new ServerSocket(5678);
            System.out.println("Server socket initialized on port 5678");
            
            while (true) {
                System.out.println("Listening for incoming connections...");
                clientConnection = serverSocket.accept();
                inputReader = new BufferedReader(
                    new InputStreamReader(clientConnection.getInputStream())
                );
                processClientData();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    private void processClientData() {
        try {
            String message;
            while ((message = inputReader.readLine()) != null) {
                System.out.println("Received from client: " + message);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            cleanupResources();
        }
    }
    
    private void cleanupResources() {
        try {
            if (inputReader != null) {
                inputReader.close();
            }
            if (clientConnection != null) {
                clientConnection.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        TcpServer server = new TcpServer();
        server.startServer();
    }
}

Client Implementation

The client application connects to the server and allows users to send messages through a simple Swing interface:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

import javax.swing.*;
import javax.swing.border.*;

public class TcpClient extends JFrame {
    private static final long serialVersionUID = 1L;
    private PrintWriter outputWriter;
    private Socket connection;
    private JTextArea messageArea;
    private JTextField inputField;
    
    public TcpClient(String title) {
        super(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initializeUI();
    }
    
    private void initializeUI() {
        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());
        
        messageArea = new JTextArea(10, 30);
        messageArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(messageArea);
        scrollPane.setBorder(new BevelBorder(BevelBorder.RAISED));
        contentPane.add(scrollPane, BorderLayout.CENTER);
        
        inputField = new JTextField();
        inputField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String userInput = inputField.getText();
                outputWriter.println(userInput);
                messageArea.append("Me: " + userInput + "\n");
                messageArea.setCaretPosition(messageArea.getDocument().getLength());
                inputField.setText("");
            }
        });
        contentPane.add(inputField, BorderLayout.SOUTH);
    }
    
    private void establishConnection() {
        messageArea.append("Attempting to connect to server...\n");
        try {
            connection = new Socket("localhost", 5678);
            outputWriter = new PrintWriter(connection.getOutputStream(), true);
            messageArea.append("Connection established successfully\n");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        TcpClient client = new TcpClient("TCP Client Application");
        client.setSize(350, 250);
        client.setVisible(true);
        client.establishConnection();
    }
}

Tags: java tcp socket Network Programming ServerSocket

Posted on Sat, 29 Aug 2026 16:04:51 +0000 by DarkPrince2005