在适当的初始化之后,这是一个无限循环来为传入的HTTPS请求提供服务,但每个请求只有一个连接(假设请求只需要一次读取):
while TRUE do
begin // wait for incoming TCP connection
if listen(listen_socket, 100) 0 then continue; // listen failed
client_len := SizeOf(sa_cli);
sock := accept(listen_socket, @sa_cli, @client_len); // create socket for connection
if sock = INVALID_SOCKET then continue; // accept failed
ssl := SSL_new(ctx); // TCP connection ready, create ssl structure
if assigned(ssl) then
begin
SSL_set_fd(ssl, sock); // assign socket to ssl structure
if SSL_accept(ssl) = 1 then // handshake worked
begin
bytesin := SSL_read(ssl, buffer, sizeof(buffer)-1);
if bytesin > 0 then
begin
buffer[bytesin] := #0;
// decide on response here...
response := 'HTTP/1.0 200 OK'#13#10 + etc;
SSL_write(ssl, pchar(response)^, length(response));
end; // else read empty or failed
end; // else handshake failed
SSL_set_shutdown(ssl, SSL_SENT_SHUTDOWN or SSL_RECEIVED_SHUTDOWN);
CloseSocket(sock);
SSL_free(ssl);
end; // else ssl creation failed
end; // while
正在改变
if ssl_accept(ssl) = 1 then
到
while ssl_accept(ssl) = 1 do
正确支持默认HTTP 1.1 keep-alive所需的所有内容(即每个连接多个请求)?
答案 0 :(得分:0)
没有。每个连接只应调用ssl_new()
和ssl_accept()
一次。连接并协商SSL会话后,无需再次执行此操作。 HTTP keep-alives旨在避免在每个请求上重新连接。您需要将调用循环到ssl_read()
和SSL_write()。
另外,不要忘记检查客户端的HTTP版本。预计HTTP 1.1客户端默认支持keep-alives,而不必请求它们。 HTTP 1.0和更早版本的客户端必须显式包含“Connection:keep-alive”请求标头。无论哪种方式,服务器都需要发送一个'Connection:close'或'Connection:keep-alive'响应头来分别通知客户端连接是关闭还是保持打开状态。
基本上,您需要实现这种模型(伪代码):
while True do
begin
accept an incoming connection...
initialize SSL...
repeat
read a request...
if not Connected then Break;
KeepAlive := ((client is HTTP1.1+) and (request['Connection'] = '')) or (request['Connection'] = 'keep-alive');
prepare reply...
response['Connection'] := iif(KeepAlive, 'keep-alive', 'close');
send reply...
while KeepAlive and Connected;
cleanup SSL...
close socket...
end;