简体   繁体   English

WebSocket握手不起作用

[英]WebSocket handshake not working

I'm making a simple WebSocket server in PHP. 我正在用PHP制作一个简单的WebSocket服务器。 My websocket client connects to it fine, but any time I try to send data through it I get an "Error: INVALID_STATE_ERR: DOM Exception 11" thrown in JavaScript. 我的websocket客户端可以很好地连接到它,但是每当我尝试通过它发送数据时,都会在JavaScript中引发“错误:INVALID_STATE_ERR:DOM异常11”。

This and a couple other questions seem to describe the same problem I'm having but the WebSocket protocol has changed since. 这个问题和其他几个问题似乎描述了我遇到的相同问题,但此后WebSocket协议已更改。

I'm assuming the problem is that my script is handshaking incorrectly as stated in that question. 我假设问题是我的脚本如该问题所述错误地握手。 I'm using Chromium 15 which uses WebSocket version 8. 我正在使用使用WebSocket版本8的Chromium 15。

Here's my handshake function (partially my code partially modified from an outdated example I found somewhere): 这是我的握手函数(部分是从在某处发现的过时示例部分修改了我的代码):

function dohandshake($user, $buffer)
{
server_log(1, 'Requesting handshake...');

// Determine which version of the WebSocket protocol the client is using
if(preg_match("/Sec-WebSocket-Version: (.*)\r\n/ ", $buffer, $match))
    $version = $match[1];
else 
    return false;

if($version == 8)
{
    // Extract header variables
    if(preg_match("/GET (.*) HTTP/"   ,$buffer,$match)){ $r=$match[1]; }
    if(preg_match("/Host: (.*)\r\n/"  ,$buffer,$match)){ $h=$match[1]; }
    if(preg_match("/Sec-WebSocket-Origin: (.*)\r\n/",$buffer,$match)){ $o=$match[1]; }
    if(preg_match("/Sec-WebSocket-Key: (.*)\r\n/",$buffer,$match)){ $k = $match[1]; }

    // Generate our Socket-Accept key based on the IETF specifications
    $accept_key = $k . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
    $accept_key = sha1($accept_key, true);
    $accept_key = base64_encode($accept_key);

    $upgrade =  "HTTP/1.1 101 Switching Protocols\r\n" .
                    "Upgrade: websocket\r\n" .
                    "Connection: Upgrade\r\n" .
                    "Sec-WebSocket-Accept: $accept_key";

    socket_write($user->socket, $upgrade, strlen($upgrade));
    $user->handshake = true;
    return true;
}
else 
{
    server_log("Client is trying to use an unsupported WebSocket protocol ({$version})");
    return false;
}
}

I tested the key generation code on several examples I found and it seems to have returned the correct key according to those examples 我在发现的几个示例中测试了密钥生成代码,并且根据这些示例似乎已经返回了正确的密钥

在本世纪的愚蠢解决方案中,握手响应结束时显然会出现两条“ \\ r \\ n”换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM