How to implement TCP IP protocol in Java?

Iris 51 Published: 10/16/2024

How to implement TCP IP protocol in Java?

I'm happy to help! However, I'll respond in Simplified Chinese as per the rules.

import java.net.*;

import java.io.*;

Socket socket = serverSocket.accept(); // accept incoming connection

InputStream in = socket.getInputStream();

OutputStream out = socket.getOutputStream();

public class EchoServer {

public static void main(String[] args) throws Exception {

ServerSocket serverSocket = new ServerSocket(8000);

Socket socket = serverSocket.accept();

InputStream in = socket.getInputStream();

OutputStream out = socket.getOutputStream();

byte[] buffer = new byte[1024];

int bytesRead;

while ((bytesRead = in.read(buffer)) != -1) {

String message = new String(buffer, 0, bytesRead);

System.out.println("Received: " + message);

out.write(message.getBytes());

out.flush();

}

in.close();

out.close();

socket.close();

}

}

TCP client server program in Java

I can respond in English for this special request! Here's a detailed explanation of the TCP client-server program in Java:

Server-side (Java)

The server code is responsible for setting up and managing the connection with the client. It runs continuously, waiting for incoming connections from clients.

import java.net.*;

import java.io.*;

public class TCPServer {

public static void main(String[] args) throws IOException {

ServerSocket serverSocket = new ServerSocket(8001);

System.out.println("Server is running...");

while (true) {

Socket socket = serverSocket.accept();

System.out.println("New connection established: " + socket.getInetAddress());

HandleClientConnection handleClient = new HandleClientConnection(socket);

handleClient.start();

}

}

private static class HandleClientConnection extends Thread {

private Socket socket;

public HandleClientConnection(Socket socket) {

this.socket = socket;

}

@Override

public void run() {

try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {

while (true) {

System.out.println("Waiting for client message...");

String inputLine = readFromSocket();

if (inputLine == null || inputLine.isEmpty()) {

break;

}

// Process the client's request

out.writeBytes("Server: " + inputLine);

out.writeBytes("n");

socket.getOutputStream().flush();

}

} catch (IOException e) {

System.out.println("Error handling client connection: " + e.getMessage());

} finally {

try {

socket.close();

} catch (IOException ignored) {}

}

}

private String readFromSocket() throws IOException {

try (DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()))) {

return in.readUTF();

}

}

}

}

Client-side (Java)

The client code is responsible for establishing a connection with the server and sending requests to it.

import java.net.*;

import java.io.*;

public class TCPClient {

public static void main(String[] args) throws IOException {

Socket socket = new Socket("localhost", 8001);

System.out.println("Connected to the server");

try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {

while (true) {

System.out.print("Enter a message for the server: ");

String inputLine = readFromStdin();

if (inputLine == null || inputLine.isEmpty()) {

break;

}

// Send the request to the server

out.writeBytes(inputLine);

out.writeBytes("n");

}

} catch (IOException e) {

System.out.println("Error connecting to the server: " + e.getMessage());

} finally {

try {

socket.close();

} catch (IOException ignored) {}

}

}

private static String readFromStdin() throws IOException {

Scanner scanner = new Scanner(System.in);

return scanner.nextLine();

}

}

How it works

The server creates a ServerSocket and listens for incoming connections on port 8001. When a client connects, the server spawns a new thread to handle that connection (HandleClientConnection). The client establishes a connection with the server using a Socket. The client sends requests to the server by writing messages to its output stream. The server processes these requests by reading from its input stream and printing responses back to the client. The client reads the server's responses and prints them to the console.

Benefits

TCP ensures reliable, error-checked data transfer between clients and servers. Multiple clients can connect to the server simultaneously without interference. The server can handle a large number of concurrent connections efficiently.

Limitations

TCP is connection-oriented, meaning that each client must establish a separate connection with the server for each request-response exchange. Clients may experience delays or timeouts if the network connection is unreliable or congested.

By using Java's built-in networking classes (java.net and java.io), you can create robust and efficient TCP client-server programs that handle multiple concurrent connections and ensure reliable data transfer.