无法使用新的websocket协议发送消息

时间:2011-05-27 18:13:04

标签: php javascript websocket

我正在尝试在php中开发一个websocket服务器。

这是我到目前为止所做的: (服务器部分)

$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($server, "localhost", 10000);
socket_listen($server);

$client = socket_accept($server);

$message = socket_read($client, 5000);

$matches = array();

preg_match('#Sec-WebSocket-Key: (.*)\r\n#', $message, $matches);

$new_key = new_key($matches[1]);

$new_message = "HTTP/1.1 101 Switching Protocols\r\n";
$new_message .= "Upgrade: websocket\r\n";
$new_message .= "Connection: Upgrade\r\n";
$new_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";

socket_write($client, $new_message, strlen($new_message));

$new_message = "Test message !";

socket_write($client, $new_message, strlen($new_message));

function new_key($key)
{
    $key .= "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    $key = sha1($key);
    $new_key = '';

    for ($i = 0; $i < strlen($key); $i+=2)
    {
        $new_key .= chr(intval($key[$i] . $key[$i+1], 16));
    }

    $new_key = base64_encode($new_key);

    return $new_key;
}

/* End of file server.php */

(客户部分)

window.onload = function() {
    var ws = new WebSocket('ws://localhost:10000');

    ws.onopen = function() {
        alert('Connection open !');

        setInterval(function() {
            ws.send('lol');
        }, 1000);
    }

    ws.onclose = function() {
        alert('WebSocket close !');
    }

    ws.onmessage = function(e) {
        alert(e.data);
    }

    ws.onerror = function(e) {
        alert('Error');
    }
};

第一个socket_write完美地工作(握手),open事件被正确触发。但第二个socket_write不起作用。我试图在ws.send事件上open在服务器部分中使用第二个socket_read,但它也不起作用。

如果您有任何想法,谢谢!

2 个答案:

答案 0 :(得分:0)

我认为它是INVALID_STATE_ERR:DOM Exception 11意味着同步问题。在您的客户端尝试此操作:

var test = function(){
    var myWebSocket = new WebSocket('ws://localhost:10000');
    myWebSocket.onopen = function(e){
        alert('connection open');
        this.send('test1');
        this.send('test2');
    }
    myWebSocket.onmessage = function(e){ alert('message ' + e.data) };
    myWebSocket.onclose = function(e){ alert('connection closed'); this.close(); };
    myWebSocket.send('test3');
};

test3将失败,因为它是一个异步websocket。

答案 1 :(得分:0)

我有类似的问题。在此处查看此项目后https://github.com/srchea/PHP-Push-WebSocket我在发送邮件之前注意到此文件https://github.com/srchea/PHP-Push-WebSocket/blob/master/lib/Server.class.php中名为“encode”的函数。

所以试着改变这个

socket_write($client, $new_message, strlen($new_message));
$new_message = "Test message !";
socket_write($client, $new_message, strlen($new_message));

到这个

socket_write($client, $new_message, strlen($new_message));
$new_message = "Test message !";
socket_write($client, chr(129) . chr(strlen($new_message)) ."". $new_message);