I am trying to implement sample HTTP server using Java socket and executor service for concurrency. However every 2nd request is failing when I run the test using JMeter with 2 or more requests or browser for example.
How to properly handle the request? Here is the sample source code:
public class Service {
public static void main(String[] args) throws Exception {
var serverSocket = new ServerSocket(8080);
var executors = Executors.newFixedThreadPool(4);
while(true) {
try {
var server = serverSocket.accept();
executors.submit(() -> {
try {
var text = "sample";
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
System.out.println("Getting empty request");
var response = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/plain\r\n" +
"Content-Length: " + text.length() + "\r\n\r\n"
+ text;
server.getOutputStream().write(response.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
System.out.println("Executor error:" + e.toString());
e.printStackTrace();
} finally {
try {
System.out.println("Closing server");
server.close();
} catch (Exception e) {
System.out.println("Executor error2: ");
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
break;
}
}
serverSocket.close();
}
}
jmeter xyz localhost:8080that demostrates how the request fails. I wouldn't be surprised if JMeter will tell you when/why the request fails. Also, is it possible this is an OS issue? Maybe include the OS and JDK you're using. It works fine for me using Linux + JDK17. I usedwgetand made about 20 requests. They all returned with the text sample