I’m stuck in the concurrent connections challenge
It works on my computer but not for the tests…
I receive from the test this output:
Creating connection 2
[tester::#EJ5] Sending first set of requests
[tester::#EJ5] client-2: $ curl -v http://localhost:4221/
[tester::#EJ5] client-2: > GET / HTTP/1.1
[tester::#EJ5] client-2: > Host: localhost:4221
[tester::#EJ5] client-2: >
[tester::#EJ5] client-2: Sent bytes: “GET / HTTP/1.1\r\nHost: localhost:4221\r\n\r\n”
[your_program] Receive a connection: /0:0:0:0:0:0:0:1
[your_program] worker started
[tester::#EJ5] Failed to read response:
[tester::#EJ5] Received: “” (no content received)
[tester::#EJ5] ^ error
[tester::#EJ5] Error: Expected: HTTP-version, Received: “”
[tester::#EJ5] Test failed
and this is how i’m reading the request:
InputStream in = this.socket.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int prev = -1, curr;
//read target and method
while (true) {
curr = in.read(); //<- HERE is the problem it hangs a little then conncection is closed
if (prev == '\r' && curr == '\n') {
break;
}
buffer.write(curr);
prev = curr;
}
String tmp = buffer.toString("UTF-8");
this.method = tmp.split(" ")[0].trim();
this.target = tmp.split(" ")[1].trim();
System.out.println("Target: " + this.target);
System.out.println("Method: " + this.method);
buffer.reset();
// Read the headers
while (true) {
curr = in.read();
buffer.write(curr);
if (buffer.size() >= 4) {
byte[] last4 = buffer.toByteArray();
int len = last4.length;
if (last4[len - 1] == '\n' && last4[len - 2] == '\r' && last4[len - 3] == '\n'
&& last4[len - 4] == '\r') {
break;
}
}
}
// Read the Headers to the MAP
String headers = buffer.toString("UTF-8");
String[] headerLines = headers.split("\r\n");
for (String header : headerLines) {
if (header.contains(":")) {
String k = header.split(":")[0].trim();
String v = header.split(":")[1].trim();
this.headers.put(k, v);
}
}
System.out.println("HEADERS: " + this.headers.toString());
// READ the body
int cl = 0;
if (this.headers.containsKey("Content-Length")) {
cl = Integer.parseInt(this.headers.get("Content-Length"));
}
this.body = new byte[cl];
int bytesRead = 0;
while (bytesRead < cl) {
int res = in.read(this.body, bytesRead, cl - bytesRead);
if (res == -1)
break;
bytesRead += res;
}