html5新api websocket初探

php socket server端:

<?php
ob_implicit_flush();
$addrss = '127.0.0.1';
$port = 9111;
$server = socket_create(AF_INET , SOCK_STREAM , SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($server , $addrss , $port);
socket_listen($server , 10);
$clients[] = $server;
tip("server started and listening on $port $servern");
$blank = false;
while(true){
socket_select($clients,$write=NULL,$except=NULL,NULL);
//echo "en";
foreach($clients as $k => $sock){
//连接主机的client
if($sock == $server){
$client = socket_accept($server);
if($client < 0){
echo 'socket_accept() failedn';
continue;
}else{
$clients[] = $client;
echo "connect clientn";
continue;
}
}else{
//$len = socket_recv($sock , $buffer , 2048 , 0);
$len=socket_recv($sock,$buffer,2048,0);
if($len < 7){
unset($clients[$k]);
continue;
}
if(!$blank){
$buf = substr($buffer,strpos($buffer,'Sec-WebSocket-Key:')+18);
$key = trim(substr($buf,0,strpos($buf,"rn")));

$new_key = base64_encode(sha1($key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));

$new_message = "HTTP/1.1 101 Switching Protocolsrn";
$new_message .= "Upgrade: websocketrn";
$new_message .= "Sec-WebSocket-Version: 13rn";
$new_message .= "Connection: Upgradern";
$new_message .= "Sec-WebSocket-Accept: " . $new_key . "rnrn";
socket_write($sock,$new_message,strlen($new_message));
$blank = true;
}else{//echo 11111111111111111111111111111;die;
$str = decode($buffer);
echo "received data:$strn";
$msg = 'hello client';
$msg = code($msg);
socket_write($sock,$msg,strlen($msg));
}

}
//$client = socket_accept($server);
//$buffer = socket_read($client, 8192);
}
}
//}
function tip($tip){
$tip = date('Y-m-d H:i:s').' : '.$tip;
echo iconv('utf-8','gbk//IGNORE',$tip);
}
function decode($buffer) {
$len = $masks = $data = $decoded = null;
$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 code($msg){
$msg = preg_replace(array('/r$/','/n$/','/rn$/',), '', $msg);
$frame = array();
$frame[0] = '81';
$len = strlen($msg);
$frame[1] = $len<16?'0'.dechex($len):dechex($len);
$frame[2] = ord_hex($msg);
$data = implode('',$frame);
return pack("H*", $data);
}
function ord_hex($data) {
$msg = '';
$l = strlen($data);
for ($i= 0; $i<$l; $i++) {
$msg .= dechex(ord($data{$i}));
}
return $msg;
}

javascript socket客户端(我修改了windows的hosts文件,把blog.f.com解析到127.0.0.1):

<script src='jquery-1.8.2.min.js'></script>
<script>
function ini()
{
var content = 'initial';
var host = 'ws://blog.f.com:9111/server.php';
socket = new WebSocket(host);
socket.onopen = function(){
//alert(socket.readyState);
//alert('socket has been opened');
socket.send(content);
}
socket.onmessage = function(msg){
alert(msg.data);
}

}
function sendChat(){
var content = $('textarea').val();
//alert(content);
socket.send(content);
}
</script>
<body onload='ini()'>
<textarea></textarea>
<input type='button' value='发送' onclick='sendChat($(this))'>
</body>

首先,在dos下执行php server.php启动9111端口箭头监听

php socket server

php socket server

打开浏览器客户端,向服务器发送数据

html5 websocket

html5 websocket

向服务器发送数据,服务器也收到了,服务器给客户端发送数据

server-client

server-client

单个客户端和服务器端建立socket链接正常,也能正常通信,但是当再开一个客户端时,就死活链接不上,chrome的js console报错:Uncaught InvalidStateError: Failed to execute ‘send’ on ‘WebSocket': Still in CONNECTING state.真心无奈.调试发现,当第二个客户端链接时,连while循环都没有进去.谁若是有解,一定请留言告诉我,谢谢!!!

评论

目前评论:0   

点击加载更多评