数据从浏览器通过websocket发送给服务器的数据,是原始的帧数据,默认是被掩码处理过的,所以需要对其利用掩码进行解码。
从服务器发送给浏览器的数据是默认没有掩码处理的,只要符合一定结构就可以了。具体可以参考websocket的RFC文档
http://www.rfcreader.com/#rfc6455
The threat model being protected against is one in which the client sends data that appears to be an HTTP request. As such, the channel that needs to be masked is the data from the client to the server. The data from the server to the client can be made to look like a response, but to accomplish this request, the client must also be able to forge a request. As such, it was not deemed necessary to mask data in both directions (the data from the server to the client is not masked)
解码函数
function decode($received)
{
$len = $masks = $data = $decoded = null;
$buffer = $received;
$len = ord($buffer[1]) & 127;
if ($len === 126) {
$masks = substr($buffer, 4, 4);
$data = substr($buffer, 8);
} else {
if ($len === 127) {
$masks = substr($buffer, 10, 4);
$data = substr($buffer, 14);
} else {
$masks = substr($buffer, 2, 4);
$data = substr($buffer, 6);
}
}
for ($index = 0; $index < strlen($data); $index++) {
$decoded .= $data[$index] ^ $masks[$index % 4];
} return $decoded;
}
编码函数:
function encode($buffer)
{
$len = strlen($buffer); $first_byte = self::BINARY_TYPE_BLOB; if ($len <= 125) {
$encode_buffer = $first_byte . chr($len) . $buffer;
} else {
if ($len <= 65535) {
$encode_buffer = $first_byte . chr(126) . pack("n", $len) . $buffer;
} else {
//pack("xxxN", $len)pack函数只处理2的32次方大小的文件,实际上2的32次方已经4G了。
$encode_buffer = $first_byte . chr(127) . pack("xxxxN", $len) . $buffer;
}
} return $encode_buffer;
}
}
服务器端代码:
<?php class WebSocket
{
const BINARY_TYPE_BLOB = "\x81";
private $socket; public function __construct($port)
{
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, 0, $port);
socket_listen($socket);
return $this ->socket = $socket;
} public function run()
{
$clients[] = $this -> socket;
while(true)
{
$read = $clients;
$write = null;
$except = null;
if(false === socket_select($read, $write, $except, null))
{
continue;
} if(in_array($this -> socket, $read))
{
echo "new request ...\n";
$clients[] = $newsock = socket_accept($this -> socket);
$request = socket_read($newsock, 321600*2);
if($this -> handshake($newsock, $request))
{
socket_getpeername($newsock, $ip);
echo "new client $ip conntected\n";
$key = array_search($this -> socket, $read);
unset($read[$key]);
}
else
{
echo "handshake failed \n";
}
} foreach ($read as $sock_read)
{
$data = socket_read($sock_read, 32160*2);
if(false === $data)
{
$key = array_search($sock_read, $clients);
socket_getpeername($clients[$key], $ip);
unset($clients[$key]);
echo "client $ip disconnected\n";
continue;
}
$data = $this -> decode($data);
$response = "recevied data len : ".strlen($data)." $data";
$response = $this -> encode($response);
socket_write($sock_read, $response, strlen($response));
}
}
socket_close($this -> socket);
} public function handshake($socket, $request)
{
if (preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $request, $match)) {
$Sec_WebSocket_Key = $match[1];
}
// Calculation websocket key.
$new_key = base64_encode(sha1($Sec_WebSocket_Key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
// Handshake response data.
$handshake_message = "HTTP/1.1 101 Switching Protocols\r\n";
$handshake_message .= "Upgrade: websocket\r\n";
$handshake_message .= "Sec-WebSocket-Version: 13\r\n";
$handshake_message .= "Connection: Upgrade\r\n";
$handshake_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n"; socket_write($socket, $handshake_message); return true;
} public function decode($received)
{
$len = $masks = $data = $decoded = null;
$buffer = $received;
$len = ord($buffer[1]) & 127;
if ($len === 126) {
$masks = substr($buffer, 4, 4);
$data = substr($buffer, 8);
} else {
if ($len === 127) {
$masks = substr($buffer, 10, 4);
$data = substr($buffer, 14);
} else {
$masks = substr($buffer, 2, 4);
$data = substr($buffer, 6);
}
}
for ($index = 0; $index < strlen($data); $index++) {
$decoded .= $data[$index] ^ $masks[$index % 4];
} return $decoded;
} public function encode($buffer)
{
$len = strlen($buffer); $first_byte = self::BINARY_TYPE_BLOB; if ($len <= 125) {
$encode_buffer = $first_byte . chr($len) . $buffer;
} else {
if ($len <= 65535) {
$encode_buffer = $first_byte . chr(126) . pack("n", $len) . $buffer;
} else {
//pack("xxxN", $len)pack函数只处理2的32次方大小的文件,实际上2的32次方已经4G了。
$encode_buffer = $first_byte . chr(127) . pack("xxxxN", $len) . $buffer;
}
} return $encode_buffer;
}
} $ws = new WebSocket(1313);
$ws -> run();
客户端代码:
$(function(){
url = "ws://localhost:1313/server.php";
socket = new WebSocket(url);
cnt = 1; socket.onopen = function()
{
socket.send("this is chrome broswer");
} socket.onmessage = function(msg)
{
$('#info').append(msg.data);
}
});
效果