swoole服务的优化--websocket面向对象服务类

服务类:

class ws{
	//定义一个属性 保存服务链接句柄
	public $ws = null;
	
	//构造函数 初始化websocket服务连接
	public function __construct(){
		$this->ws = new swoole_websocket_server('0.0.0.0',8811);
		
		$this->ws->on('open',[$this,'onOpen']);
		$this->ws->on('message',[$this,'onMessage']);
		$this->ws->on("close",[$this,"onClose"]);
		$this->ws->start();
	} 
	public function onOpen($ws,$request){
		echo $request->fd."上线\n";
	}
	public function onMessage($ws,$frame){
			echo "来自".$frame->fd."的信息".date("Y/m/d H:i:s").":".$frame->data."\n";
			$ws->push($frame->fd,"您在".date("Y/m/d H:i:s")."给服务器发送消息:".$frame->data);
	}
	public function onClose($ws,$fd){
		echo $fd."下线了\n ";
	}
	
	
}
   
$obj = new ws();

至此,一个简单websocket协议就可以测试了

猜你喜欢

转载自blog.csdn.net/qq_17040587/article/details/82984068
今日推荐