超简单的HTTP套接字服务器,用PHP编写的,工作不正常 [英] Ultra simple HTTP socket server, written in PHP, behaving unexpectedly
问题描述
tldr;
- 在
PHP很小的流套接字服务器
- 行为奇怪,因为有时它成功用于
HTTP
要求和有时非常相同的过程 中失败 - 的行为在不同的浏览器奇怪的 - 几乎每一次失败中
铬
键,从来没有在IE11
- very minimal stream socket server in
PHP
- acts strange since sometimes it successfully serves
HTTP
request and sometimes fails within the very same process - acts strange across different browsers - almost every time fails in
Chrome
and never inIE11
code:
$server = stream_socket_server("tcp://0.0.0.0:4444", $errno, $errorMessage);
if ($server === false)
throw new UnexpectedValueException("Could not bind to socket: $errorMessage");
$e = "\r\n";
$headers = array(
"HTTP/1.1 200 OK",
"Date: " . date('D') . ', ' . date('m') . ' ' . date('M') . ' ' . date('Y') . ' ' . date('H:i:s') . ' GMT' ,
'Server: MySpeedy',
'Connection: close',
'Content-Type: text/plain',
'Content-Length: 2'
);
$headers = implode($e, $headers) . $e . $e .'ok';
for (;;)
{
$client = stream_socket_accept($server);
if ($client)
{
echo 'Connection accepted from '.stream_socket_get_name($client, false) . $e;
fwrite($client, $headers);
fclose($client);
}
}
给我这个HTTP响应(远程登录的结果):
gives me this http response (telnet results):
HTTP/1.1 200 OK
Date: Fri, 11 Nov 2015 20:09:02 GMT
Server: MySpeedy
Connection: close
Content-Type: text/plain
Content-Length: 2
ok
这使我的结果:
-
ERR_CONNECTION_RESET
在Chrome中,几乎每一次(20-30也许1
请求得到预期的反应) -
连接被重置
在Firefox中,大约1 2-3
请求 - 在Internet Explorer中11每次都正确,预期的响应(耶,
IE浏览器是最好的东西)。
ERR_CONNECTION_RESET
in Chrome, almost every time (maybe 1 in 20-30 requests get expected response)The connection was reset
in Firefox, approximately 1 in 2-3 requests- Correct, expected response in Internet Explorer 11 every time (yay, IE is the best in something).
我是什么做错了吗?它是长达 HTTP头(我不能说,如果我的格式不正确它们)或插座回路或..?
What am I doing wrong? Is it up to http headers (I couldn't say if I've formatted them incorrectly) or socket loop or..?
推荐答案
您没有从客户端读取HTTP请求,而是简单地把您回应并关闭连接。但关闭套接字,同时还有数据读取会导致连接复位发送回客户端,这就是你会在Chrome中看到ERR_CONNECTION_RESET。其他浏览器可能不同的表现,这也是一个时机的问题,如果浏览器可以显示操作复位前的响应。
You don't read the HTTP request from the client but instead simply send your response and close the connection. But closing the socket while there are still data to read will cause a connection reset send back to the client and that's what you will see in Chrome with ERR_CONNECTION_RESET. Other browsers might behave differently and it is also a timing issue if the browser can display the response before handling the reset.
要解决这个问题首先从客户端读取完整的请求关闭套接字之前。
To fix it first read the full request from the client before you close the socket.
这篇关于超简单的HTTP套接字服务器,用PHP编写的,工作不正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!