zoukankan      html  css  js  c++  java
  • thinkphp5.0整合workerman实现简单聊天室

    具体配置请看上一篇文档。

    Worker.php 文档代码
    <?php
    
    namespace apphttpcontroller;
    
    use thinkworkerServer;
    
    class Worker extends Server
    {
        protected $socket = 'websocket://127.0.0.1:2346';
        protected $processes = 1;
        /**
         * 收到信息
         * @param $connection
         * @param $data
         */
        public function onMessage($connection, $data)
        {
    
            $worker = $this->worker;
            $id = $connection->id;
            foreach ($worker->connections as $connection){
                $connection->send($id .'说:'.$data);
            }
        }
    
        /**
         * 当连接建立时触发的回调函数
         * @param $connection
         */
        public function onConnect($connection)
        {
    
        }
    
        /**
         * 当连接断开时触发的回调函数
         * @param $connection
         */
        public function onClose($connection)
        {
    
        }
    
        /**
         * 当客户端的连接上发生错误时触发
         * @param $connection
         * @param $code
         * @param $msg
         */
        public function onError($connection, $code, $msg)
        {
            echo "error $code $msg
    ";
        }
    
        /**
         * 每个进程启动
         * @param $worker
         */
        public function onWorkerStart($worker)
        {
    
        }
    }
    

    ws_test.html 代码

      

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>workerman</title>
    </head>
    <body>
    
        内容: <input type="text" id="test1" >
        <button type="submit" id="btn" onclick="Submit()" >提交</button>
    
    </body>
    
    <div id="div_box">
    
    </div>
    
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
        ws = new WebSocket("ws://127.0.0.1:2346");
        ws.onopen = function() {
        };
    
        function Submit() {
            var uid1 = document.getElementById('test1').value;
            ws.send(uid1);
            document.getElementById('test1').value="";
        }
    
        ws.onmessage = function(e){
            // console.log(e.data);
            $('#div_box').after('<div id="div_box">
    ' +
                '
    ' + e.data +
                '</div>')
        };
    
    </script>
    
    </html>
    

    实测结果

      

  • 相关阅读:
    selenium ide 录制回放link链接报错
    如何打造个人技术影响力
    如何打造个人技术影响力
    三个Bootstrap免费字体和图标库
    程序媛,坚持这几个好习惯让你越来越美
    程序媛,坚持这几个好习惯让你越来越美
    程序媛,坚持这几个好习惯让你越来越美
    程序媛,坚持这几个好习惯让你越来越美
    [慕课笔记]mongodb入门篇
    [慕课笔记]mongodb入门篇
  • 原文地址:https://www.cnblogs.com/ihuangjianxin/p/13963044.html
Copyright © 2011-2022 走看看