For a project I am trying to setup a TCP connection between a client and a webserver. When I do a get request to the root of the webserver I first get a 200(OK) response but after that the webserver sends a 400(Bad request) response. Note that I do not send any extra requests so this is the second response on my first request. The webserver I have running is a simple node.js server that returns "Hello World".
Request to the webserver
GET / HTTP/1.1
Host: localhost:8001
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7
Response from the webserver
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Tue, 18 Aug 2020 09:13:06 GMT
Connection: keep-alive
Transfer-Encoding: chunked
c
Hello world
0
HTTP/1.1 400 Bad Request
Connection: close
Code for the webserver
var http = require("http");
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello world\n')
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
I found the answer to my problem and it's so simple that it took me two days to find it. My buffer that I use to send to the webserver over the tcp connection was 4096 bytes long but my message was a lot shorter. The emtpy bytes were sent over a separate request and resulted in the 400 Bad Request response. I now trim my buffers to eliminate all the empty space in them before I send any requests. Thanks to all that helpes me!!