我尝试在没有任何框架的纯php上创建我的第一个简单的websocket。我已经成功地从php向多个客户端发送了消息,但是现在我想从js向php发送消息,但是我总是失败。你能告诉我我做错了什么吗?这是我的php代码:
$clients=array();
$address='127.0.0.1';
$port=9988;
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
//socket_set_option($socket,SOL_SOCKET,SO_REUSEADDR,1);
socket_bind($socket,$address,$port);
socket_listen($socket);
socket_set_nonblock($socket);
while(true){
sleep(1);
$newc=socket_accept($socket);
if($newc!==false){
//echo "Client ".$newc." has connected<br />\r\n";
$clients[]=$newc;
$request=socket_read($newc,5000);
preg_match('#Sec-WebSocket-Key: (.*)\r\n#',$request,$matches);
$key=base64_encode(pack('H*',sha1($matches[1].'258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
$headers="HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Accept: $key\r\n\r\n";
socket_write($clients[count($clients)-1],$headers,strlen($headers));
}
foreach($clients as $client){
$content='Now: '.time();
$response=chr(129).chr(strlen($content)).$content;
socket_write($client,$response);
/*@socket_recv($socket,$buf,8192,0);
echo "Client ".$client." has sent \"".$buf."\"<br />\r\n";*/
}
}
这是我的js代码:
<html>
<body>
<div id="root"></div>
<script>
var host='ws://127.0.0.1:9988/socket.php';
var socket=new WebSocket(host);
socket.onmessage=function(e){
document.getElementById('root').innerHTML=e.data;
};
setInreval(function(){
websocket.send(JSON.stringify({data:Math.random()*(max-min)+min}));
},500)
</script>
</body>
</html>
如您所见,我尝试从js向php发送随机数,但无法在php中获取它。.
任何有帮助的人!谢谢!