繁体   English   中英

Websocket无法打开连接

[英]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方法后,因为它的行为不正确并引发错误...

暂无
暂无

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

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