我正在PHP中开发一个简单的websocket服务器.我知道有很多现有的实现,但我想让自己的,以便更好地学习协议.我设法做好握手,我的客户端连接到服务器.我还设法对客户端的数据进行解码,但是在发回消息时遇到问题.当客户端接收到我的响应时,客户端断开连接. Firefox说与ws:// localhost:12345 /的连接在页面加载时被中断..
这是我的代码来包装数据:
private function wrap($msg = ""){
$length = strlen($msg);
$this->log("wrapping (" . $length . " bytes): " . $msg);
$bytesFormatted = chr(129);
if($length <= 125){
$bytesFormatted .= chr($length);
} else if($length >= 126 && $length <= 65535) {
$bytesFormatted .= chr(126);
$bytesFormatted .= chr(( $length >> 8 ) & 255);
$bytesFormatted .= chr(( $length ) & 255);
} else {
$bytesFormatted .= chr(127);
$bytesFormatted .= chr(( $length >> 56 ) & 255);
$bytesFormatted .= chr(( $length >> 48 ) & 255);
$bytesFormatted .= chr(( $length >> 40 ) & 255);
$bytesFormatted .= chr(( $length >> 32 ) & 255);
$bytesFormatted .= chr(( $length >> 24 ) & 255);
$bytesFormatted .= chr(( $length >> 16 ) & 255);
$bytesFormatted .= chr(( $length >> 8 ) & 255);
$bytesFormatted .= chr(( $length ) & 255);
}
$bytesFormatted .= $msg;
$this->log("wrapped (" . strlen($bytesFormatted) . " bytes): " . $bytesFormatted);
return $bytesFormatted;
}
更新:我用Chrome尝试过,并在控制台中打印出以下错误:服务器不得遮挡发送给客户端的任何帧.
我把一些控制台打印输出到服务器上.它是一个基本的echo服务器.我试着用aaaa所以实际包装的消息必须是6个字节.对?
Chrome会打印上述错误.还要注意,封装消息后,我只需将其写入套接字:
$sent = socket_write($client, $bytesFormatted, strlen($bytesFormatted));
$this->say("! " . $sent);
它打印6意味着6字节实际上写入电线.
如果我尝试使用aaa,Chrome不会打印错误,但也不会调用我的onmessage处理程序.它挂起来好像等待更多的数据.
任何帮助高度赞赏.谢谢.