• swoole完成聊天室


    1.swoole使用swoole_event_add()注册事件完成聊天室

    客户端代码

    <?php
        $socket = stream_socket_client("tcp://127.0.0.1:9501",$errno,$errstr,30);
        function onRead(){
            global $socket;
            $buffer = stream_socket_recvfrom($socket,1024);
            if(!$buffer){
                swoole_event_del($socket);
            }
            echo "REV{$buffer}".PHP_EOL;
            fwrite(STDOUT,"Enter MSG");
        }
    
        function onWrite(){
            global $socket;
            echo "ON write".PHP_EOL;
    
        }
        function onInput(){
            global $socket;
            $msg = trim(fgets(STDIN));
            if($msg == "exit"){
                swoole_event_exit();
                exit();
            }
            swoole_event_write($socket,$msg);
            fwrite(STDOUT, "Enter Msg".PHP_EOL);
        }
    
        swoole_event_add($socket,'onRead','onWrite');
        swoole_event_add(STDIN,"onInput");
    
    ?>

    2.服务端代码

    <?php
    class Server{
        private $serv;
        private $test;
    
        public function __construct(){
            $this->serv = new swoole_server("0.0.0.0",'9501');
            $this->serv->set([
                'worker_num'=>2,
            ]);
            $this->serv->on('Start',[$this,'onStart']);
            $this->serv->on('Connect',[$this,'onConnect']);
            $this->serv->on("Close",[$this,'onClose']);
            $this->serv->on('Receive',[$this,'onReceive']);
            $this->serv->start();
        }
    
        public function onStart($serv){
            echo "Start".PHP_EOL;
        }
    
        public function onConnect($serv,$fd,$from_id){
            echo "Client connect".PHP_EOL;
        }
    
        public function onClose($serv,$fd,$from_id){
            echo "Client close connections".PHP_EOL;
        }
    
        public function onReceive($serv,$fd,$from_id,$data){
            echo "GET Message From Client".PHP_EOL;
            echo $data.PHP_EOL;
            foreach($serv->connections as $client){
                    if($fd != $client){
                        $serv->send($client,$data);
                    }
            }
        }
    }
    
    $Server = new Server();
  • 相关阅读:
    zenity命令显示图形框
    noVNC实现浏览器远程访问VNC服务
    获取Linux系统网卡IP网关mac等信息shell脚本
    Linux实现图形化选择文件并转码
    金仓数据库部署V8R6集群
    UOS专业版怎么开启SSH
    金仓数据量逻辑备份还原
    金仓数据库物理备份还原
    [yolov5] Learn and practice
    抖音视频怎么去水印
  • 原文地址:https://www.cnblogs.com/zh718594493/p/12897666.html
Copyright © 2020-2023  润新知