我正在尝试编写自己的HTTP 1.1服务器,只是为了好玩并更多地了解HTTP、套接字和线程。
我已经开始了静态页面的交付(使用C语言,目前我希望继续使用它)。我有一个测试页面,根据Chrome的说法,在不使用线程或保持活动套接字的情况下,可以在124毫秒内交付其大约50个文件。
我发现很难使线程/保持活动完全工作。在网络上几乎没有任何资源(在我数小时的谷歌搜索中找不到),详细解释保持活动连接。如果有人能推荐一本关于HTTP服务器编程的好书,我将非常感激。
我以前通过制作简单的聊天程序来进行过一些线程和套接字编程,因此我至少有一些经验。
我的问题是,当我尝试合并线程时,客户端浏览器会建立多个连接。在某个地方,服务器混淆了,客户端只是坐在那里等待响应,而服务器停止做任何事情。我发送Connection:Keep-Alive标头,但这并没有改变任何内容,当我合并keep-alive并创建一个用于在线程函数中获取请求的循环时,它会停顿直到连接关闭。
如果有人能给我一些伪代码,告诉我如何使保持活动/线程为此工作,以便客户端停止同时创建多个连接,我将不胜感激。
下面是正在发生的事情的简要描述:
主函数
load in static pages to large array of fileinfo struct that hold the file data and length
create the socket
set it to listen to port 80
set it to listen for 10 connections at a time(i know this is low...)
start an endless loop
block while waiting for someone to connect
check if it's a localhost connection
shutdown the server
otherwise
start a thread(with pthread), sending it the socket variable
loop
线程函数
setsock opt for 3 sec timeout on send/recv and enable Keep-alive
start endless loop
read in request
if request timed out, break the loop
Validate Request function call
Create Reponse function call
Send response
if request contained Connection: close header break the loop
loop
close socket
return