1. 程式人生 > 實用技巧 >thinkphp5.0整合workerman實現簡單聊天室

thinkphp5.0整合workerman實現簡單聊天室

具體配置請看上一篇文件。

Worker.php 文件程式碼
<?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 程式碼

  

<!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>

實測結果