//封装单例模式(三私一公)
class SwooleWebSocket
{
private static $instance; //存放当前对象属性
private static $server; //存放webSocket对象属性
private $dir = 'swooleLogs/swoole.log';
private function __construct() {
//创建webSocket对象
self::$server = new Swoole\WebSocket\Server('0.0.0.0', 9505);
//设置参数
self::$server->set([
'daemonize' => 1, // 作为守护进程运行,需同时设置log_file
'log_file' => $this->dir, // 指定标准输出和错误日志文件
]);
//注册事件
self::$server->on('open',[$this,'onOpen']); //将当前类中的onOpen方法作为open的事件处理函数
self::$server->on('message',[$this,'onMessage']);
self::$server->on('close',[$this,'onClose']);
}
private function __clone() {
// TODO: Implement __clone() method.
trigger_error('Clone is not allowed !');
}
public static function getInstance() {
if ( !(self::$instance instanceof self) ){
self::$instance = new self();
}
return self::$instance;
}
//当前客户端连接之后要执行的方法
public function onOpen($server,$request) {
echo "client: {$request->fd}\n";
$server->push($request->fd, "hello, welcome\n");
}
//当客户端向服务器发送消息时要执行的方法
public function onMessage($server,$frame) {
//处理业务逻辑
echo "client: {$frame->data}\n";
$server->push($frame->fd, "server: {$frame->data}");
}
//当客户端和服务端断开连接时要执行的方法
public function onClose($server,$fd) {
echo "client-{$fd} is closed\n";
}
//启动webSocket方法
public static function start(){
self::$server->start();
}
}
SwooleWebSocket::getInstance()->start();