WebSocket服务器使用最新协议(hybi 10)

2bs*_*dev 4 html5 websocket phpwebsocket

我在这里浏览了论坛,这是我发现的最接近的问题:

如何(de)在WebSockets hybi 08+中构建数据框架?

不同之处在于我无法获得成功的握手.我假设在握手完成之后,框架不会发挥作用,这是正确的吗?

当Chrome方便地更新到使用HyBi 10 websocket协议(http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10)的版本14时,我即将发布概念验证.根据握手规范中的信息(http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10#section-5.2.2),我已经能够成功创建一个Sec-WebSocket - 接受键(基于他们的例子成功),但在客户端,socket.onopen函数永远不会触发.

上次我遇到了WebSocket协议握手的问题,这是一个用正确的字节终止握手的问题(或者我认为字符更准确?).我正在使用PHP进行当前的实现,这意味着尝试解码Python或C#实现,到目前为止还没有成功.

以下是我在Chrome 14(适用于Windows)中运行的客户端Javascript:

var socket;
socket = new WebSocket(host);
socket.onopen = function(msg){
    // process onopen
};
socket.onmessage = function(msg){ 
    // process message
};
socket.close = function(msg){
    // process close
};
Run Code Online (Sandbox Code Playgroud)

这是我的握手服务器端PHP代码:

function dohandshake($user,$buffer){
    // getheaders and calcKey are confirmed working, can provide source if desired
    list($resource,$host,$origin,$key,$version) = $this->getheaders($buffer);
    $request = "HTTP/1.1 101 Switching Protocols\r\n" .
            "Upgrade: WebSocket\r\n" .
            "Connection: Upgrade\r\n" .
            "Sec-WebSocket-Accept: " . $this->calcKey($key) . "\r\n";
    socket_write($user->socket,$request);
    $user->handshake=true;
    return true;
}
Run Code Online (Sandbox Code Playgroud)

一旦客户端发送初始握手,Javascript套接字将无限期地保持在CONNECTING状态.这意味着onopen永远不会被解雇,因此我的套接字处于不稳定状态.关于如何调试,甚至更好地确认我的握手方法的任何想法都会很棒.

这是Python(https://github.com/kanaka/websockify/blob/master/websocket.py)中的一个明显的(我不能说它是否有效).查找do_handshake方法.

谢谢!

2bs*_*dev 5

所以我通过握手解决了我的特殊问题,而且非常无聊.我需要两套"\ r \n"来关闭握手.所以为了解决我上面描述的握手问题(Javascript WebSocket没有进入OPEN状态)我需要对我的服务器端PHP进行以下更改(注意最后的\ r \n\r \n,doh) :

function dohandshake($user,$buffer){
    // getheaders and calcKey are confirmed working, can provide source if desired
    list($resource,$host,$origin,$key,$version) = $this->getheaders($buffer);
    $request = "HTTP/1.1 101 Switching Protocols\r\n" .
        "Upgrade: WebSocket\r\n" .
        "Connection: Upgrade\r\n" .
        "Sec-WebSocket-Accept: " . $this->calcKey($key) . "\r\n\r\n";
    socket_write($user->socket,$request);
    $user->handshake=true;
    return true;
}
Run Code Online (Sandbox Code Playgroud)

同样对于未来的PHP-WebSocket爱好者,我只是使用正则表达式来解析getheaders中的头部,这是calcKey:

function calcKey($key){
     $CRAZY = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
     $sha = sha1($key.$CRAZY,true);
     return base64_encode($sha);
}
Run Code Online (Sandbox Code Playgroud)

希望这有助于其他人!现在来处理消息框架......