Websocket不会打开连接

时间:2012-09-08 13:06:53

标签: php javascript html5 sockets 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();
}

1 个答案:

答案 0 :(得分:0)

问题出在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();
}

删除了日志方法,因为这行为不正确并抛出错误......