Websocket赢得';t打开连接


Websocket won't open connection

在过去的几个小时里,我一直在与websocket作斗争,无法将其连接起来!

以下是握手协议:

GET /websocket/Server.php HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:10020
Origin: http://localhost:8888
Sec-WebSocket-Key: fWN5C0N5EqQ/EnYET9C8DQ==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
Cookie: SQLiteManager_currentLangue=2
MY RESPONSE:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: P3XPDvAuKuz0RoHKq8oDrGHRM9c=

我用来写响应的PHP函数是:

function handle13Protocol($req){
  $info = array();
  $MAGICSTRING = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  if(preg_match("/GET (.*) HTTP/"   ,$req,$match)){ $info["GET"]=$match[1]; }
  if(preg_match("/Host: (.*)'r'n/"  ,$req,$match)){ $info["HOST"]=$match[1]; }
  if(preg_match("/Origin: (.*)'r'n/",$req,$match)){ $info["ORIGIN"]=$match[1]; }
  if(preg_match("/Sec-WebSocket-Key: (.*)'r'n/",$req,$match)){ $info["KEY"]=$match[1]; }
  if(preg_match("/'r'n(.*?)'$/",$req,$match)){ $data=$match[1]; }
  echo "key = ".$info["KEY"]."'n";
  $acceptKey = base64_encode(sha1($info["KEY"].$MAGICSTRING,true));
  $upgrade =  "HTTP/1.1 101 Switching Protocols'r'n" .
               "Upgrade: websocket'r'n" .
               "Connection: Upgrade'r'n" .
               "Sec-WebSocket-Accept: $acceptKey".
                "'r'n'r'n" ;
  echo $upgrade;
  return $upgrade;  
}

在我的控制台上,它没有出现任何错误,而且它说插座没有断开。

然而,我的javascript不会确认我的连接,即onopen函数。我甚至尝试了这个复制粘贴部分,以确保我有正确的js:

alert("Connecting to server now");
function init(){
  var host = "ws://localhost:10020/websocket/Server.php";
  try{
    socket = new WebSocket(host);
    log('WebSocket - status '+socket.readyState);
    socket.onopen    = function(msg){ alert("opened!"); };
    socket.onmessage = function(msg){ log("Received: "+msg.data); };
    socket.onclose   = function(msg){ log("Disconnected - status "+this.readyState); };
  }
  catch(ex){ log(ex); }
  $("msg").focus();
}

问题出在javascript中。正确的JS是

alert("Connecting to server now");
function init(){
  var host = "ws://localhost:10020/websocket/Server.php";
  try{
    socket = new WebSocket(host);
    socket.onopen    = function(msg){ alert("opened!"); };
    socket.onmessage = function(msg){ log("Received: "+msg.data); };
    socket.onclose   = function(msg){ log("Disconnected - status "+this.readyState); };
  }
  catch(ex){ log(ex); }
  $("msg").focus();
}

删除了log方法,因为它的行为不正确,并引发了一个错误。。。