0

在过去的几个小时里,我一直在与 websockets 作斗争,但无法连接!

这些是握手协议:

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();
}
4

1 回答 1

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();
}

删除 log 方法后,因为它的行为不正确并引发错误...

于 2012-09-08T15:15:02.123 回答