Ratchet实现PHP WebSocket多人聊天功能的示例

  

  • composer 安装ratchet
    composer require cboden/ratchet
  • 使用PDO连接数据库,创建mysql命令如下
    CREATE TABLE messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        message TEXT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );
  • 使用Redis存储消息列表

这个示例代码中,PHP代码使用Ratchet来创建WebSocket服务器,并实现了简单的聊天功能。HTML代码使用JavaScript来建立WebSocket连接,并处理消息传输和用户输入。要运行此代码,请确保已安装Ratchet并在终端中运行PHP文件。然后,通过打开浏览器并访问HTML代码所在的地址,就可以开始聊天了。

 在onMessage方法中,我们首先将接收到的消息存入Redis列表中。然后,如果Redis中的消息数量超过1000,则将所有消息取出并依次存入MySQL中。请注意,在MySQL中执行多个INSERT语句时,最好使用事务(即BEGIN、COMMIT语句)来确保数据的完整性。

 WebSocket服务端代码:

<?php

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

require_once __DIR__ . '/vendor/autoload.php';

class Chat implements MessageComponentInterface
{
    protected $clients;
    protected $pdo;
    protected $redis;

    public function __construct()
    {
        $this->clients = new \SplObjectStorage;

        // 连接到数据库
        $dsn = 'mysql:host=localhost;dbname=chat';
        $username = 'root';
        $password = '';
        $options = [
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
            \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
        ];
        $this->pdo = new \PDO($dsn, $username, $password, $options);

        // 连接到 Redis
        $this->redis = new \Redis();
        $this->redis->connect('localhost', 6379);
    }

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg)
    {
        foreach ($this->clients as $client) {
            if ($from !== $client) {
                $client->send($msg);
            }
        }

        // 将消息存入 Redis
        $this->redis->rpush('messages', $msg);

        // 如果 Redis 中的消息数量超过 1000,则将消息存入数据库
        if ($this->redis->llen('messages') > 1000) {
            $messages = $this->redis->lrange('messages', 0, -1);

            // 开始事务
            $this->pdo->beginTransaction();

            foreach ($messages as $message) {
                // 将消息存入数据库
                $stmt = $this->pdo->prepare('INSERT INTO messages (message) VALUES (?)');
                $stmt->execute([$message]);

                // 从 Redis 中删除已经存入数据库的消息
                $this->redis->lpop('messages');
            }

            // 提交事务
            $this->pdo->commit();
        }
    }

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}

$webSocketServer = new \Ratchet\WebSocket\WsServer(new Chat());
$server = \Ratchet\Server\IoServer::factory(
    new \Ratchet\Http\HttpServer($webSocketServer),
    8080
);

$server->run();

 开启socket服务命令,假设php文件名为socket.php

php ./socket.php

 HTML代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket Chat</title>
</head>
<body>
    <div id="messages"></div>
    <form>
        <input type="text" id="message" placeholder="Enter message">
        <button type="submit">Send</button>
    </form>
    
    <script>
        var conn;
        var connect = function() {
            conn = new WebSocket('ws://localhost:8080');
            
            conn.onopen = function(e) {
                console.log("Connection established!");
            };
            
            conn.onmessage = function(e) {
                var messages = document.getElementById("messages");
                var message = document.createElement("div");
                message.innerHTML = e.data;
                messages.appendChild(message);
            };
            
            conn.onclose = function(e) {
                console.log("Connection closed, attempting to reconnect...");
                setTimeout(connect, 1000);
            };
        };
        
        connect();
        
        var form = document.querySelector("form");
        var input = document.querySelector("#message");
        
        form.addEventListener("submit", function(e) {
            e.preventDefault();
            
            conn.send(input.value);
            input.value = "";
        });
    </script>
</body>
</html>

保证WebSocket服务一直开启,可以使用一个常驻进程管理工具supervisor,使用supervisor的示例配置链接

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值