r/codedbyhand • • 17d ago

How to implement Keep alive connection in an HTTP low level Socket connection?

I was trying to recreate an HTTP/HTTPS request Library in C. I want to implement and use the Connection: keep-alive header in my program. I started with setsockopt() all that jazz to set it up, but it still doesn't work. When I start the program for a connection: close, it prints out the html, however whenever I do it for a keep-alive, it just keeps running without ever printing anything.

15 Upvotes

3 comments sorted by

4

u/YouPeopleCantBeReal4 17d ago

If you’re using http, to keep a connection live you would use websockets which is HTTP/1.1 since that is the http level that introduced persistent connection

2

u/emnotbr 17d ago edited 17d ago

No, http 1.0 it was required that you specify the type of connection, otherwise default would be close. HTTP 1.1 an open connection is enabled by default, unless otherwise specified by the server. The main issue with my program was how I was using my recv function, I was using a while loop where the bytes being received had to be greater than 0. However in an open connection, it never sends 0 bytes to signal a connection close.

edit: I meant otherwise specified by the server, or the client.

2

u/emnotbr 17d ago

Wait nvm I had to set the HTTP version to 1.0 lol. But why does that work?