-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTcpServer.java
More file actions
36 lines (29 loc) · 1.09 KB
/
TcpServer.java
File metadata and controls
36 lines (29 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package org.example;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
private final int port;
public TcpServer(int port) {
this.port = port;
}
public void start() {
System.out.println("Starting TCP server on port " + port);
try (ServerSocket serverSocket = new ServerSocket(port)) {
while (true) {
Socket clientSocket = serverSocket.accept(); // block
System.out.println("Client connected: " + clientSocket.getRemoteSocketAddress());
Thread.ofVirtual().start(() -> handleClient(clientSocket));
}
} catch (IOException e) {
throw new RuntimeException("Failed to start TCP server", e);
}
}
private void handleClient(Socket client) {
try (ConnectionHandler connectionHandler = new ConnectionHandler(client)) {
connectionHandler.runConnectionHandler();
} catch (Exception e) {
throw new RuntimeException("Error handling client connection " + e);
}
}
}