Irgendeine Idee warum? (Hinweis: Das folgende Beispiel wird unter Windows 11 PC getestet) < /p>
Code: Select all
public class TcpServer {
public static void main(String[] args) throws Exception {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(8090), 500);
while (true) {
var socketChannel = serverSocketChannel.accept();
System.out.println("client connected: " + socketChannel.getRemoteAddress());
socketChannel.close();
}
}
}
< /code>
public class TcpStressTest {
static AtomicInteger successCount = new AtomicInteger(0);
static AtomicInteger failureCount = new AtomicInteger(0);
public static void main(String[] args) throws Exception {
// create 10k threads to connect to server
int N = 250;
ExecutorService executorService = java.util.concurrent.Executors.newFixedThreadPool(50);
List futures = new java.util.ArrayList();
for (int i = 0; i < N; i++) {
Future submit = executorService.submit(() -> {
TcpClient client = new TcpClient();
int start = client.start();
if (start == 1) {
successCount.incrementAndGet();
} else {
failureCount.incrementAndGet();
}
});
futures.add((Future) submit);
}
for (Future future : futures) {
try {
future.get();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("All clients finished");
System.out.println("Success count: " + successCount.get());
System.out.println("Failure count: " + failureCount.get());
}
}
< /code>
public class TcpClient {
private static final String SERVER_HOST = "localhost";
private static final int SERVER_PORT = 8090;
public int start() {
try {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new java.net.InetSocketAddress(SERVER_HOST, SERVER_PORT));
socketChannel.close();
return 1;
} catch (java.io.IOException e) {
System.out.println("[Thread: " + Thread.currentThread().getName() + " Connection failed: " + e.getMessage());
return 0;
}
}
}
Mobile version