温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

workerman实现群聊

发布时间:2020-08-09 06:03:24 来源:网络 阅读:564 作者:Lee_吉 栏目:web开发
  1. 服务端:
    <?php
    require_once "vendor/autoload.php";
    use dollarphp\autofunction;
    use dollarphp\errorhandle;
    new autofunction('function');
    new errorhandle();
    use Workerman\Worker;
    use GatewayWorker\Gateway as gate;
    use GatewayWorker\BusinessWorker;
    use GatewayWorker\Register;
    use GatewayWorker\Lib\Gateway;
    $gateway = new gate("websocket://0.0.0.0:2345");
    $gateway->startPort = 30000;
    $gateway->count = 4;
    $gateway->name = 'gateway';
    $gateway->registerAddress = '127.0.0.1:1234';
    $business = new BusinessWorker();
    $business->count = 4;
    $business->registerAddress = '127.0.0.1:1234';
    $register = new Register('text://0.0.0.0:1234');
    $register->name = 'register';
    class Events{
    public static function onConnect($client_id){
        return GateWay::sendToCurrentClient('welcome');
    }
    public static function onMessage($client_id, $message){
        $arr = array(
                'remote_ip'=>$_SERVER['REMOTE_ADDR'],
                'remote_port'=>$_SERVER['REMOTE_PORT'],
                'gate_ip'=>$_SERVER['GATEWAY_ADDR'],
                'gate_port'=>$_SERVER['GATEWAY_PORT'],
                'client_id'=>$_SERVER['GATEWAY_CLIENT_ID'],
            );
        var_dump($arr);
        return GateWay::sendToCurrentClient($message);
    }
    public static function onClose($client_id){
       GateWay::sendToAll("client[$client_id] logout\n");
    }
    }
    Worker::runAll();
  2. 客户端:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    </head>
    <body>
    <input type="text">
    <br>
    <input type="button" value="提交">
    <script>
        var ws = new WebSocket('ws://192.168.8.81:2345')
        ws.onopen = function(data) {
            console.log('连接开始\n')
        }
        ws.onmessage = function(data) {
            console.log('接收消息:'+data.data)
        }
        ws.onclose = function(data) {
            console.log('关闭连接\n')
        }
        ws.onerror = function(data) {
            console.log('遇到错误\n')
        }
        var text = document.getElementsByTagName('input')[0]
        var button = document.getElementsByTagName('input')[1]
        button.onclick = function(){
            var val = text.value
            ws.send(val)
        }
    </script>
    </body>
    </html>
  3. 效果:
    workerman实现群聊
    workerman实现群聊
    workerman实现群聊
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI