stream_socket_server不起作用,但socket_create工作

时间:2017-05-04 08:12:32

标签: php websocket

我正在尝试在php5 +&中使用websocket win7x64环境。 首先,我使用stream_socket_server通过php-websocket示例创建服务器套接字(保存为test_socket1.php)

....
$url = 'tcp://127.0.0.1:8000';
$this->context = stream_context_create();
if(!$this->master = stream_socket_server($url, $errno, $err, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $this->context))
{
   die('Error creating socket: ' . $err);
}   
$this->allsockets[] = $this->master;
$this->log('Server created');   
....
....
public function run()
{
    while(true)
    {
        $changed_sockets = $this->allsockets;
        @stream_select($changed_sockets, $write = null, $except = null, 0, 5000);   
        foreach($changed_sockets as $socket)
        {
            if($socket == $this->master)
            {
                if(($ressource = stream_socket_accept($this->master)) === false)
                {
                    $this->log('Socket error: ' . socket_strerror(socket_last_error($ressource)));
                    continue;
                }
                else
                {
....

运行命令:php test_socket1.php,得到“Server created”输出。 之后,我在chrome / IE中运行client.html,它将进入stream_select而不会返回超时。 所以我使用另一个例子PHP-Websockets,它使用socket_create,(保存为test_socket2.php)

....    
$this->master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)  or die("Failed: socket_create()");
socket_set_option($this->master, SOL_SOCKET, SO_REUSEADDR, 1) or die("Failed: socket_option()");
socket_bind($this->master, '127.0.0.1', '8000')                      or die("Failed: socket_bind()");
socket_listen($this->master,20)                               or die("Failed: socket_listen()");
$this->sockets['m'] = $this->master;
$this->stdout("Server started\nMaster socket: ".$this->master);
....

运行命令:php test_socket2.php,得到“Server started ...”输出。然后我运行相同的client.html,工作正常,受到尊重。为什么这个有用? client.html如下,

var host = "ws://127.0.0.1:8000"; // SET THIS TO YOUR SERVER
try {
    socket = new WebSocket(host);
    log('WebSocket - status '+socket.readyState);
    socket.onopen    = function(msg) { 
                           log("Welcome - status "+this.readyState); 
                       };
    socket.onmessage = function(msg) { 
                           log("Received: "+msg.data); 
                       };
    socket.onclose   = function(msg) { 
                           log("Disconnected - status "+this.readyState); 
                       };
}
catch(ex){ 
    log(ex); 
}

我还在test_socket1中添加了一些检查点,试图找出问题但运气不好并且有几个未使用的结果,

  1. @stream_select - >不会返回任何内容,但client.html的“WebSocket连接到'ws://127.0.0.1:8000'失败:WebSocket打开握手超时”响应。
  2. 将“@stream_select”更改为“@socket_select”(我知道它是愚蠢的),然后它得到非零返回但是从“stream_socket_accept”收到错误,“警告:stream_socket_accept():接受失败:连接超时... “并且client.html得到了”WebSocket连接到'ws://127.0.0.1:8000'失败:HTTP身份验证失败;没有可用的有效凭据“,看起来服务器正在等待客户端的响应,客户端正在等待服务器的握手。
  3. 所以我的问题是为什么这两者有不同的结果? stream_socket需要更多预配置的东西吗?感谢。

0 个答案:

没有答案