thinkphp5.0整合workerman实现简单聊天室

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

1
Worker.php 文档代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
 
namespace app\http\controller;
 
use think\worker\Server;
 
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\n";
    }
 
    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
 
    }
}

 

ws_test.html 代码

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!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">\n' +
            '\n' + e.data +
            '</div>')
    };
 
</script>
 
</html>

 

实测结果

  

posted @   柠檬没我萌  阅读(1023)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示