laravel使用Workerman搭建简易聊天室

前言


laravel5.4实现 -> http://www.jianshu.com/p/d808dfa8b2d7
以下正文


实现一个简易的聊天室,
到这里为止通过对照那篇文章感觉swoole跟workerman实现还是挺像的.

参考了文档还有一篇文章↓

http://www.workerman.net/doc
 http://www.jianshu.com/p/4ad04f8ff907

app/Console/Commands/Workerman.php

argument('action');
        switch ($arg) {
            case 'start':
                $this->info('workerman observer started');
                $this->start();
                break;
            case 'stop':
                $this->info('stoped');
                break;
            case 'restart':
                $this->info('restarted');
                break;
        }
    }

    private function start()
    {
        global $text_worker;
        // 创建一个Worker监听9130端口,使用http协议通讯
        $text_worker = new Worker("websocket://0.0.0.0:9130");
/*        $http_worker->transport = 'http';*/
        // 启动4个进程对外提供服务
        $text_worker->count = 4;
        $handler = \App::make('handler\WorkermanHandler');
        $text_worker->onConnect = array($handler,"handle_connection");
        $text_worker->onMessage = array($handler,"handle_message");
        $text_worker->onClose = array($handler,"handle_close");

        // 运行worker
        Worker::runAll();
    }

    protected function getArguments()
    {
        return array(
            array('action',InputArgument::REQUIRED,'start|stop|restart'),
            );
    }

}

app/handle/WorkermanHandler.php

uid = ++$global_uid;
      foreach($text_worker->connections as $conn){
        $conn->send("user:[{$connection->uid}] online");
      }
    }

    //当客户端发送消息过来时,转发给所有人
    public function handle_message($connection,$data){
      global $text_worker;
      foreach($text_worker->connections as $conn){
        $conn->send("user:[{$connection->uid}] said:$data");
      }
    }

    //当客户端断开时,广播给所有客户端
    public function handle_close($connection){
      global $text_worker;
      foreach($text_worker->connections as $conn){
        $conn->send("user:[{$connection->uid}] logout");
      }
    }
    
}

你可能感兴趣的:(laravel使用Workerman搭建简易聊天室)