【黄啊码】thinkphp6结合workerman、websocket案例

2021-09-26 10:45:29 浏览数 (2)

安装workerman教程看这里——》https://cloud.tencent.com/developer/article/1882506

更改配置服务的路径:

注意这里:支持数组定义多个服务的

html代码

代码语言:javascript复制
<!DOCTYPE html>  
<html>  
<head>  
<title>HTML5</title>  
<meta charset="utf-8" />  
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>  
<script>  
$(function() {      
    var socket;  
    var readyState = ["connecting", "connected", "closing", "closed"];  
    /* 打开连接事件 */  
    $("button:eq(0)").click(function() {  
        try {  
             /* 连接 */  
            //  socket = new WebSocket("ws://39.96.9.241:6789");  
             socket = new WebSocket("ws://127.0.0.1:2346");
             /* 绑定事件 */  
             socket.onopen = function() {  
                 $("#msg").html("连接成功...");  
             };  
               
            socket.onmessage = function(e) {  
                 $("#msg").html($("#msg").html()   "<br />"   e.data);  
             };  
               
             socket.onclose = function() {  
                 $("#msg").html($("#msg").html()   "<br />关闭连接...");  
             };  
        } catch(exception) {  
            $("#msg").html($("#msg").html()   "<br />有错误发生");  
        }  
    });  
      
    /* 发送数据事件 */  
    $("button:eq(1)").click(function() {  
        /* 检查文本框是否为空 */  
        if($("#data").val() == "") {  
            alert("请输入数据!");  
            return;  
        }  
          
        try {  
            socket.send($("#data").val());  
            $("#msg").html($("#msg").html()   "<br />发送数据:"   $("#data").val());  
        } catch (exception) {  
            $("#msg").html($("#msg").html()   "<br />发送数据出错");  
        }  
          
        /* 清空文本框 */  
        $("#data").val("");  
    });  
      
    /* 断开连接 */  
    $("button:eq(2)").click(function() {  
        socket.close();  
    });  
});  
</script>  
</head>  
  
<body>  
<h1>WebSocket示例</h1>  
<input type="text" id="data" />  
<button>打开连接</button>  
<button>发送数据</button>  
<button>关闭连接</button>  
<p id="msg"></p>  
</body>  

php代码

代码语言:javascript复制
<?php 

namespace appservicecontroller;

use thinkfacadeView;
use thinkworkerServer;
use thinkfacadeSession;
use GatewayClientGateway;

// require_once '../vendor/autoload.php';
// use appindexmodelMemberfriend;
// use appindexmodelMember;
class Worker extends Server{

    protected $socket = 'websocket://0.0.0.0:2346';

    protected $client_id;

    public function onMessage($connection, $data)
    {
        dump($data);
        $connection->send("rqwerqwerqwer");
        
    }

    /**
     * 当连接建立时触发的回调函数
     * @param $connection
     */
    public function onConnect($connection)
    {
        // 生成一个唯一用户的客户端id
        $this->client_id = time().rand(100,999);
        // 将生成的client_id赋给当前连接
        $connection->client_id = $this->client_id;

        //$this->worker->transport='ssl';
        // 在当前worker对象中新添属性  保存当前登录的用户的client_id 和 连接对象
        // 以便进行推送
        $this->worker->clientIdConnections[$connection->client_id] = $connection;

        // 将生成的client_id发送给客户端
        $json = [
            'type'  =>  'bind',
            'from'  =>  'worker',
            'to'    =>  $connection->client_id,
            'content' => $this->client_id
        ];
        $connection->send(json_encode($json,true));
    }

    /**
     * 当连接断开时触发的回调函数
     * @param $connection
     */
    public function onClose($connection)
    {
        
    }

    /**
     * 当客户端的连接上发生错误时触发
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "error $code $msgn";
    }

    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {

    }
    
}

案例结果如下:

附加workman心跳案例

代码语言:javascript复制
<?php
require_once __DIR__ . '/Workerman/Autoloader.php';
use WorkermanWorker;
use WorkermanLibTimer;

// 心跳间隔55秒
define('HEARTBEAT_TIME', 55);

$worker = new Worker('text://0.0.0.0:2345');

$worker->onMessage = function($connection, $msg) {
    // 给connection临时设置一个lastMessageTime属性,用来记录上次收到消息的时间
    $connection->lastMessageTime = time();
    // 其它业务逻辑...
};

// 进程启动后设置一个每10秒运行一次的定时器
$worker->onWorkerStart = function($worker) {
    Timer::add(10, function()use($worker){
        $time_now = time();
        foreach($worker->connections as $connection) {
            // 有可能该connection还没收到过消息,则lastMessageTime设置为当前时间
            if (empty($connection->lastMessageTime)) {
                $connection->lastMessageTime = $time_now;
                continue;
            }
            // 上次通讯时间间隔大于心跳间隔,则认为客户端已经下线,关闭连接
            if ($time_now - $connection->lastMessageTime > HEARTBEAT_TIME) {
                $connection->close();
            }
        }
    });
};

Worker::runAll();

0 人点赞