namespace ws;
class ws
{
const host = "0.0.0.0";
const PORT = 8812;
public $ws = null;
public function __construct()
{
$this->ws = new \swoole_websocket_server(self::host, self::PORT);
$this->set();
$this->ws->on('open', [$this, 'onOpen']);
$this->ws->on('message', [$this, 'onMessage']);
$this->ws->on('close', [$this, 'onClose']);
$this->ws->start();
}
public function set(){
$this->ws->set([
'document_root' => '/var/www/swoole/data',
'enable_static_handler' => true,
]);
}
/**
* 当WebSocket客户端与服务器建立连接并完成握手后会回调此函数。
*/
public function onOpen($ws, $request){
echo "open: fd{$request->fd}\n";
}
/**
* 当服务器收到来自客户端的数据帧时会回调此函数。
* @param $ws
* @param $frame swoole_websocket_frame对象,包含了客户端发来的数据帧信息
* User: hhcycj
*/
public function onMessage($ws, $frame){
echo "message: receive from {$frame->fd}:{$frame->data}, opcode:{$frame->opcode}, finish:{$frame->finish}\n";
$this->ws->push($frame->fd, "this is server");
}
/**
* @param $ser
* @param $fd
* User: hhcycj
*/
public function onClose ($ser, $fd) {
echo "client {$fd} closed\n";
}
}
$obj = new ws();