thinkphp8中使用workerman实现简单的消息推送案例

1、下载thinkphp8框架

      在项目路径进入终端,输入以下代码下载thinkphp8框架:

       composer create-project topthink/think demo

2、进入项目根目录   

      cd demo

3、下载 workerman 扩展

      composer require topthink/think-worker

4、在项目根目录创建 server 文件夹,文件夹与 app 文件夹平级

5、在server文件夹下 创建  WebSocketServer.php 文件,文件中的代码为:

      

<?php  
require_once __DIR__ . '/../vendor/autoload.php';  
use Workerman\Worker;  

// 创建一个WebSocket Server监听在8888端口  
$worker = new Worker("websocket://0.0.0.0:8889");  

// 存储连接的数组  
$clients = []; 

// 存储房间信息  
$rooms   = []; 

// 处理新连接  
$worker->onConnect = function ($connection) use (&$clients) {  
    $clients[$connection->id] = $connection; // 使用客户端ID作为键  
    echo "新连接: {$connection->id}\n";  
};  

// 处理接收到的消息  
$worker->onMessage = function ($connection, $data) use (&$clients, &$rooms) {  
    $message = json_decode($data, true); // 解析JSON数据  

    if (isset($message['type']) && $message['type'] === 'join') {  
        // 加入房间  
        $roomName = $message['room'];  
        $rooms[$roomName][$connection->id] = $connection;  
        $connection->send("你已加入房间: " . $roomName);  
    } elseif (isset($message['type']) && $message['type'] === 'message') {  
        // 发送给特定房间  
        $roomName = $message['room'];  
        // 检查房间是否存在  
        if (isset($rooms[$roomName])) {  
            foreach ($rooms[$roomName] as $client) {  
                if ($client !== $connection) { // 不发送给自己  
                    $client->send("客户端 {$connection->id} 在房间 {$roomName} 说: " . $message['msg']);  
                }  
            }  
        } else {  
            $connection->send("房间 $roomName 不存在");  
        }  
    } else {  
        $connection->send("未识别的消息类型");  
    }  
};  

// 处理连接关闭  
$worker->onClose = function ($connection) use (&$clients, &$rooms) {  
    // 从 clients 数组中移除关闭的连接  
    unset($clients[$connection->id]);  
    
    // 移除连接在房间中的记录  
    foreach ($rooms as $roomName => $roomClients) {  
        if (isset($roomClients[$connection->id])) {  
            unset($rooms[$roomName][$connection->id]);  
            echo "客户端 {$connection->id} 离开了房间 {$roomName}\n";  
        }  
    }  
    
    echo "连接关闭: {$connection->id}\n";  
};  

// 启动工作进程  
Worker::runAll();

6、在public目录下创建一个 index.html 文件,代码如下:

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <title>WebSocket Test</title>  
</head>  
<body>  
    <h1>WebSocket Test</h1>  
    <input id="roomInput" type="text" placeholder="输入房间名..." />  
    <button id="joinButton">加入房间</button>  
    <input id="messageInput" type="text" placeholder="输入消息..." />  
    <button id="sendButton">发送</button>  
    <div id="response"></div>  

    <script>  
        const ws = new WebSocket("ws://you_server_ip:8889");  
        const responseDiv = document.getElementById("response");  
        const sendButton = document.getElementById("sendButton");  
        const messageInput = document.getElementById("messageInput");  
        const joinButton = document.getElementById("joinButton");  
        let currentRoom = "";  

        ws.onmessage = function(event) {  
            // 显示服务器返回的消息  
            responseDiv.innerHTML += "<p>" + event.data + "</p>";  
        };  

        // 加入房间  
        joinButton.onclick = function() {  
            const roomName = document.getElementById("roomInput").value;  
            if (roomName) {  
                currentRoom = roomName;  
                ws.send(JSON.stringify({type: 'join', room: roomName}));  
            }  
        };  

        // 发送消息  
        sendButton.onclick = function() {  
            const message = messageInput.value;  
            if (currentRoom && message) {  
                ws.send(JSON.stringify({type: 'message', room: currentRoom, msg: message}));  
                messageInput.value = ''; // 清空输入框  
            }  
        };  
    </script>  
</body>  
</html>

  7、在项目根目录 进入终端,输入下面代码启用  WebSocketServer.php 服务:

     php server/WebSocketServer.php start

  8、然后进入浏览器输入:服务器ip/index.html 进入网站

  9、如果不行的话需要配置 服务器安全组、服务器防火墙,确保端口可以流入  

10、注意事项:如果直接复制代码,你需要按照 ctrl + H 搜索 :you_server_ip,替换为你自己的服务器IP地址

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值