PHP WebSocket 实例

使用 Ratchet(无须 Swoole扩展)实现的 WebSocket 服务端完整代码,以及一个基于 HTML 的服务端监控界面

1. PHP WebSocket 服务端代码

ws_server.php

<?php
require __DIR__ . '/vendor/autoload.php';

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;

class MyWsServer implements MessageComponentInterface {
    protected $clients;

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

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
        echo "新连接!({$conn->resourceId})\n";
        $conn->send("欢迎连接到 WebSocket 服务器!");
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        echo "收到消息: $msg\n";
        // 广播给所有客户端
        foreach ($this->clients as $client) {
            if ($from !== $client) {
                $client->send("其他人说: $msg");
            } else {
                $client->send("你说: $msg");
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
        echo "连接关闭: {$conn->resourceId}\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "发生错误: {$e->getMessage()}\n";
        $conn->close();
    }
}

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new MyWsServer()
        )
    ),
    8080 // 监听端口
);

echo "WebSocket 服务器启动,监听端口 8080 ...\n";
$server->run();

2. 服务端 HTML 监控/交互界面

ws_server_admin.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>WebSocket 服务端监控界面</title>
    <style>
        #log { border:1px solid #ccc; height:300px; overflow:auto; padding:10px; margin-bottom:10px;}
    </style>
</head>
<body>
    <h2>WebSocket 服务端监控</h2>
    <div id="log"></div>
    <input id="msg" type="text" placeholder="输入要发送的消息">
    <button onclick="sendMsg()">发送</button>
    <script>
        // 注意端口要与 PHP 服务端一致
        const ws = new WebSocket("ws://127.0.0.1:8080");

        ws.onopen = function() {
            log("已连接到 WebSocket 服务器");
        };

        ws.onmessage = function(event) {
            log("收到消息: " + event.data);
        };

        ws.onerror = function(event) {
            log("WebSocket 错误: " + JSON.stringify(event));
        };

        ws.onclose = function() {
            log("连接已关闭");
        };

        function sendMsg() {
            const input = document.getElementById('msg');
            const message = input.value.trim();
            if (ws.readyState === WebSocket.OPEN && message) {
                ws.send(message);
                log("发送消息: " + message);
                input.value = '';
            }
        }

        function log(msg) {
            const logDiv = document.getElementById('log');
            logDiv.innerHTML += msg + "<br>";
            logDiv.scrollTop = logDiv.scrollHeight;
        }
    </script>
</body>
</html>

3. 配置与运行步骤

1. 安装 Composer 及 Ratchet

  1. 安装 Composer(如果没有)
    Composer官网安装教程
  2. 创建项目目录并安装 Ratchet
    composer require cboden/ratchet
    
  3. 将 ws_server.php 保存到项目目录下
    并确保 vendor 目录在同一目录下。

2. 启动 PHP WebSocket 服务端

php ws_server.php
  • 若看到“WebSocket 服务器启动,监听端口 8080 …”说明启动成功。
  • 服务端窗口会显示客户端连接和消息。
  • 可以使用如下方法在后台运行你的 php ws_server.php,并能方便地关闭
    #后台运行:
    nohup php ws_server.php > ws_server.log 2>&1 &
    #查看进程:
    ps aux | grep ws_server.php
    #关闭进程:
    kill 12345 或 pkill -f ws_server.php
    #实时查看日志输出
    tail -f ws_server.log

     


3. 使用 HTML 监控界面

  1. 将 ws_server_admin.html 放到本地任意目录(比如 ws_demo 下)。
  2. 用浏览器直接打开该 HTML 文件(无需放到 web 服务器,只需双击或file:///方式即可)。
  3. 可以发送消息、接收消息,服务端窗口会显示相关日志。

4. 让其他设备接入

  • 若要让局域网其他机器接入,把 ws://127.0.0.1:8080 改成你的服务器内网 IP,如 ws://192.168.1.100:8080,并确认防火墙允许 8080 端口访问。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注