t4web/websocket

ZF2 模块。WebSocket 服务器

dev-master 2016-07-26 10:43 UTC

This package is auto-updated.

Last update: 2024-08-26 17:46:44 UTC


README

ZF2 模块。基于 Ratchet 的 WebSocket 服务器

安装

只需 require t4web/websocket 并将其添加到您的 application.config.php 中的 T4web\Websocket

运行

在控制台中运行

$ php public/index.php websocket start

配置

在您的 global.config.php 中添加

't4web-websocket' => [
    'server' => [
        // required
        'port' => 8088,

        // not required, default 0
        'debug-enable' => 1,
    ],
];

快速使用

为测试创建 html(或从 https://github.com/t4web/Websocket/blob/master/ws-test.html 复制)

<html lang="en">
    <body>
        <input type="text" id="input" placeholder="Message…" />
        <hr />
        <pre id="output"></pre>

        <script>
            var host   = 'ws://127.0.0.1:8088';
            var socket = null;
            var input  = document.getElementById('input');
            var output = document.getElementById('output');
            var print  = function (message) {
                var samp       = document.createElement('samp');
                samp.innerHTML = message + '\n';
                output.appendChild(samp);
                return;
            };

            input.addEventListener('keyup', function (evt) {
                if (13 !== evt.keyCode) {
                    return;
                }

                var msg = {
                    'event' : 'ping',
                    'data': {message: input.value}
                };

                if (!msg) {
                    return;
                }

                try {
                    print('Send: ' + JSON.stringify(msg, null, 4));
                    socket.send(JSON.stringify(msg));
                    input.value = '';
                    input.focus();
                } catch (e) {
                    console.log(e);
                }

                return;
            });

            try {
                socket = new WebSocket(host);
                socket.onopen = function () {
                    print('connection is opened');
                    input.focus();
                    return;
                };
                socket.onmessage = function (msg) {
                    print('Receive: ' + JSON.stringify(JSON.parse(msg.data), null, 4));
                    return;
                };
                socket.onclose = function () {
                    print('connection is closed');
                    return;
                };
            } catch (e) {
                console.log(e);
            }
        </script>
    </body>
</html>

或从 PHP

/** @var \T4web\Websocket\WebsocketClient $wsClient */
$wsClient = $this->getServiceLocator()->get(\T4web\Websocket\Client::class);
$wsClient->send('ping', ['message' => 'Hello World']);

建议的架构

每个 WebSocket 请求消息必须是 JSON 对象

{
    "event": "event-name",
    "data": { "field": "value" }
}

WebSocket 响应消息

{
    "event": "event-name",
    "data": { "field": "value" },
    "error": "string|null"
}

每个 WebSocket 请求消息 - 您可以处理。只需在 module.config.php 中的 t4web-websocket[event-handlers] 描述自己的处理器

't4web-websocket' => [
    'event-handlers' => [
        // event name => handler - Callable object
        'ping' => Handler\Ping::class,
    ],
],

处理器\Ping :

use SplObjectStorage;
use Ratchet\ConnectionInterface;

class Ping implements T4web\Websocket\Handler\HandlerInterface
{
    public function handle($eventName, array $data, ConnectionInterface $connection, SplObjectStorage $connections)
    {
        $response = [
            'event' => 'pong',
            'data' => $data,
            'error' => null,
        ];
        $connection->send(json_encode($response));
    }
}