swoole聊天室

运行 php swoole.php

浏览器打开  index.html

文件swoole.php

class user{

public $user =[];
private static $instance;
/**
* 返回单例
* @return CLIENT_Accuse
*/

public static function getInstance()
{
if(!isset(self::$instance))
{
self::$instance = new self();
}
return self::$instance;
}
public function getAll(){
return $this->user;
}
public function set($key,$value){
$this->user[$key] = $value;
return $this->user;
}
public function del($key){
unset($this->user[$key]);
}
}
//官网demo
$server = new swoole_websocket_server("192.168.8.198", 9501);
$server->on('open', function (swoole_websocket_server $server, $request) {
echo "server: handshake success with fd{$request->fd}\n";//$request->fd 是客户端id
});
$server->on('message', function (swoole_websocket_server $server, $frame) {
echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},finish:{$frame->finish}\n";
$server->push($frame->fd, "this is server");//$frame->fd 是客户端id,$frame->data是客户端发送的数据
//服务端向客户端发送数据是用 $server->push( '客户端id' ,  '内容')
user::getInstance()->set($frame->fd,"opcode:{$frame->opcode},finish:{$frame->finish}");
print_r(user::getInstance()->getAll());
});
$server->on('close', function ($ser, $fd) {
echo "client {$fd} closed\n";
user::getInstance()->del($fd);
print_r(user::getInstance()->getAll());
});

$server->start();

++++++++++++++++++++++++++html code+++++++++++++++++++++++++

index.html

<input id="content" type="text" />
<button data-ke-onclick="exampleSocket.send( document.getElementById('content').value )">发送</button>


<button data-ke-onclick="exampleSocket.send( document.getElementById('content').value )"></button>
Posted in : php


发表评论

电子邮件地址不会被公开。 必填项已用*标注