Building TCP Connections in Java Using Sockets

Understanding Network Sockets

Network applications communicate through endpoints known as sockets. A socket serves as an abstraction for a network connection, relying on the underlying TCP/IP protocols managed by the operating system to route data. Programming languages like Java supply classes such as ServerSocket and Socket to wrap these native OS-level functions.

IP addresses alone are insufficient for directing traffic because a single machine hosts numerous concurrent applications (e.g., web browsers, email clients). When a packet arrives, the OS requires a mechanism to route it to the correct process. Sockets solve this by combining an IP address with a port number. Ports range from 0 to 65535; ports below 1024 are restricted to privileged processes, while those above are available for general use.

In a typical TCP interaction, one application acts as the server, binding to a specific port and listening for incoming requests. The other acts as the client, initiating a connection to the server's IP and port. Upon successful connection, a reliable bidirectional channel is established. The server's socket remains bound to its fixed port, while the client's socket utilizes an ephemeral port dynamically assigned by the OS.

File Transfer Implementation

Receiver (Server) Implementation

public class FileReceiver {
    public static void main(String[] args) {
        int listenPort = 9900;
        
        try (var listener = new ServerSocket(listenPort)) {
            System.out.println("Waiting for connections on port " + listenPort);
            
            while (true) {
                try (var connection = listener.accept();
                     var dataInput = new BufferedInputStream(connection.getInputStream());
                     var fileOutput = new BufferedOutputStream(new FileOutputStream("received_data.jpg"));
                     var responseWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()))) {
                     
                    System.out.println("Connection established from: " + connection.getInetAddress());
                    
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    
                    while ((bytesRead = dataInput.read(buffer)) != -1) {
                        fileOutput.write(buffer, 0, bytesRead);
                    }
                    fileOutput.flush();
                    
                    responseWriter.write("Transfer complete");
                    responseWriter.newLine();
                    responseWriter.flush();
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Sender (Client) Implementation

public class FileSender {
    public static void main(String[] args) {
        String targetHost = "127.0.0.1";
        int targetPort = 9900;
        String sourceFile = "sample_image.jpg";
        
        try (var remoteServer = new Socket(targetHost, targetPort);
             var fileInput = new BufferedInputStream(new FileInputStream(sourceFile));
             var networkOutput = new BufferedOutputStream(remoteServer.getOutputStream());
             var responseReader = new BufferedReader(new InputStreamReader(remoteServer.getInputStream()))) {
             
            byte[] payload = new byte[4096];
            int bytesRead;
            
            while ((bytesRead = fileInput.read(payload)) != -1) {
                networkOutput.write(payload, 0, bytesRead);
            }
            networkOutput.flush();
            
            remoteServer.shutdownOutput();
            
            String serverResponse;
            while ((serverResponse = responseReader.readLine()) != null) {
                System.out.println("Server acknowledgment: " + serverResponse);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Tags: java tcp Socket Programming Network Communication

Posted on Sun, 10 May 2026 21:32:25 +0000 by gushy