Skip to content

Commit 37a2020

Browse files
committed
Add blocking TCP server using ServerSocket
1 parent 658c3ca commit 37a2020

2 files changed

Lines changed: 34 additions & 2 deletions

File tree

src/main/java/org/example/App.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
public class App {
44
public static void main(String[] args) {
5-
System.out.println("Hello There!");
6-
5+
SocketServer.main();
76
}
87
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package org.example;
2+
3+
import java.io.IOException;
4+
import java.net.ServerSocket;
5+
import java.net.Socket;
6+
7+
public class SocketServer {
8+
9+
static void main() {
10+
int port = 3000;
11+
12+
try (ServerSocket serverSocket = new ServerSocket(port, 64)) {
13+
14+
System.out.println("Server started at port: " + serverSocket.getLocalPort());
15+
16+
while (true) {
17+
Socket socket = serverSocket.accept();
18+
Thread.ofVirtual().start(() -> handleClient(socket));
19+
}
20+
21+
} catch (IOException e) {
22+
throw new RuntimeException(e);
23+
}
24+
}
25+
26+
static void handleClient(Socket socket) {
27+
try {
28+
socket.close();
29+
} catch (IOException e) {
30+
e.printStackTrace();
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)