workerman实现群聊

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了workerman实现群聊相关的知识,希望对你有一定的参考价值。

  1. 服务端:
    <?php
    require_once "../vendor/autoload.php";
    use Workerman\Worker;
    $worker = new Worker(‘websocket://0.0.0.0:2345‘);
    $worker->count = 1;
    $worker->onWorkerStart = function($data){
    echo "连接开始\n";
    };
    $worker->onConnect = function($data){
    echo "连接完成\n";
    };
    $worker->onMessage = function($con,$data) use ($worker){
    echo "接收消息:{$data}\n";
    foreach($worker->connections as $id=>$connection){
        $connection->send($id.‘:‘.$data);
    }
    };
    $worker->onClose = function($data){
    echo "关闭连接\n";
    };
    $worker->onError = function($data){
    echo "遇到错误\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实现群聊的主要内容,如果未能解决你的问题,请参考以下文章

php workerman怎么用

F3 workerman 群发及客户端和socket服务器保持长连接双向消息推送

使用workerman实现在线聊天-第一版

WorkerMan源码分析 - 实现最简单的原型

workerman实现简单弹幕的方法

swoole和workerman哪个更易开发