@
feiyuanqiu 代码。。。。我一开始就是嫌太长了所以没发。。。。
<?php
set_time_limit(0);
class ws{
public $sock;
public $socks;
public $users;
function send($socket,$msg){
if($socket==="all"){
foreach ($this->user as $key => $value) {
socket_write($this->user[$key]['client'],$msg,strlen($msg));
}
}
socket_write($socket,$msg,strlen($msg));
}
function handshake($socket,$data){
$secretkey = substr($buffer,strpos($data,'Sec-WebSocket-Key:')+18);
$skey = trim(substr($secretkey,0,strpos($secretkey,"\r\n")));
$newskey = base64_encode(sha1($key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));//生成返回的握手包key,后面的字符串是固定的,不知道谁规定的。。。
$httpheader = "HTTP/1.1 101 Switching Protocols\r\n";
$httpheader .= "Upgrade: websocket\r\n";
$httpheader .= "Connection: Upgrade\r\n";
$httpheader .= "Sec-WebSocket-Accept: ".$newskey."\r\n\r\n";
send($socket,$httpheader);
$key = search($socket);
$this->users[($key-1)]["new"]=false;
return true;
}
function search($socket){
foreach ($this->socks as $key => $value) {
if($socket===$value)
return $key;
}
}
function close($socket){
socket_close($socket);
$key = search($socket);
unset($this->socks[$key]);
if($key!==0)
unset($this->user[($key-1)]);
return true;
}
function __construct($ip,$port){
$this->sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($this->sock,$ip,$port);
socket_listen($this->sock);
$this->socks[] = $this->sock;
while(1){
$sockscache = $this->socks;
socket_select($sockscache,$write = null,$expect =null,null);
foreach($sockscache as $sockcache){
if($sockcache === $this->sock){
$client = socket_accept($this->sock);
$this->socks[] = $client;
$this->users[] = array("client"=>$client,"name"=>"","new"=>true);
}else{
$length = socket_recv($sockcache,$data,2048,0);
$key = search($sockcache);
if($length<7){
$name = $this->users[($key-1)]["name"];
send($sockcache,"$name 已经退出。");
close($sockcache);
}else{
if($this->user[($key-1)]["new"]){
handshake($sockcache,$data);
}else{
//信息处理
echo $data;
die();
}
}
}
}
}
}
}
$websocket = new ws("127.0.0.1","1077");