首页 > 其他 > 详细

swoole完成聊天室

时间:2020-05-15 23:34:07      阅读:80      评论:0      收藏:0      [点我收藏+]

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();

 

swoole完成聊天室

原文:https://www.cnblogs.com/zh718594493/p/12897666.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!