【发布时间】:2016-02-15 12:46:51
【问题描述】:
tldr;
-
PHP中非常小的流套接字服务器 - 表现得很奇怪,因为有时它会成功处理
HTTP请求,而有时会在同一个进程中失败 -
在不同的浏览器中表现得很奇怪 - 几乎每次都在
Chrome中失败,而在IE11中从未失败
代码:
$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 响应(telnet 结果):
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 请求得到预期的响应) -
The connection was reset在 Firefox 中,大约 2-3 分之一 请求 - 每次在 Internet Explorer 11 中都得到正确的预期响应(是的, IE 是最好的)。
我做错了什么?是 http 标头(我不能说我的格式是否错误)还是 socket loop 或..?
【问题讨论】:
-
有时会失败 - 会发生什么?你如何使用它? (您的实现无法处理多个连接)
-
php myserver.php在控制台中,然后127.0.0.1:4444通过浏览器 -
在
Chrome中我得到ERR_CONNECTION_RESET,例如(它几乎总是在Chrome中失败) -
你会考虑回答费德里科的第一个问题吗?
-
请编辑问题而不是在 cmets 中回答,这样问题在您离开后很长一段时间内仍然有用。
标签: php apache sockets http http-headers