我正在尝试用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: (.*)rn#', $message, $matches);
$new_key = new_key($matches[1]);
$new_message = "HTTP/1.1 101 Switching Protocolsrn";
$new_message .= "Upgrade: websocketrn";
$new_message .= "Connection: Upgradern";
$new_message .= "Sec-WebSocket-Accept: " . $new_key . "rnrn";
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不起作用。我尝试在服务器部分用第二个socket_read
对open
事件执行ws.send
,但都不起作用。
如果你有想法,谢谢你!
我认为这是INVALID_STATE_ERR:DOM异常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。
我也遇到了类似的问题。在这里查看此项目后https://github.com/srchea/PHP-Push-WebSocket我注意到这个文件中有一个名为"encode"的函数https://github.com/srchea/PHP-Push-WebSocket/blob/master/lib/Server.class.php在发送消息之前。
所以试着改变这个
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);