Mastering WebSocket with Webman: From Handshake to Real‑Time Messaging

This guide explains WebSocket fundamentals, shows the HTTP handshake process, provides JavaScript client examples, and walks through a full server‑side implementation using the high‑performance PHP Webman framework with the GatewayWorker plugin, including installation, configuration, and advanced message handling.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
Mastering WebSocket with Webman: From Handshake to Real‑Time Messaging

What is WebSocket

WebSocket is a protocol that provides full‑duplex communication over a single TCP connection. After an initial HTTP‑like handshake, the client and server keep a persistent connection, allowing the server to push data without additional requests.

Handshake

Client request
GET /chat HTTP/1.1
Host: wss.tinywan.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Server response
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat

Simple JavaScript client

var ws = new WebSocket("wss://echo.websocket.org");

ws.onopen = function (evt) {
    console.log("Connection open ...");
    ws.send("Hello WebSockets!");
};

ws.onmessage = function (evt) {
    console.log("Received Message: " + evt.data);
    ws.close();
};

ws.onclose = function (evt) {
    console.log("Connection closed.");
};

WebSocket service with Webman and GatewayWorker

Installation

Webman is a high‑performance PHP framework. Install the GatewayWorker plugin via Composer: composer require webman/gateway-worker The command resolves the following packages (excerpt):

- webman/gateway-worker (v1.0.8)
- workerman/gateway-worker (v3.1.1)
- tinywan/jwt (v1.8.2)
- workbunny/webman-nacos (1.1.7)

Configuration

After installation the configuration directory is created under the Webman project (e.g. config/gateway_worker.php). The process model consists of a Gateway, BusinessWorker and Register process. Example configuration:

use Webman\GatewayWorker\Gateway;
use Webman\GatewayWorker\BusinessWorker;
use Webman\GatewayWorker\Register;

return [
    'gateway' => [
        'handler'    => Gateway::class,
        'listen'     => 'websocket://0.0.0.0:8783',
        'count'      => cpu_count(),
        'reloadable' => false,
        'constructor'=> [
            'config' => [
                'lanIp'          => '127.0.0.1',
                'startPort'      => 2300,
                'pingInterval'   => 25,
                'pingData'        => '{"type":"ping"}',
                'registerAddress'=> '127.0.0.1:12306',
                'onConnect'      => function () {},
            ]
        ]
    ],
    'worker' => [
        'handler'    => BusinessWorker::class,
        'count'      => cpu_count() * 2,
        'constructor'=> [
            'config' => [
                'eventHandler'    => plugin\webman\gateway\Events::class,
                'name'            => 'ChatBusinessWorker',
                'registerAddress' => '127.0.0.1:12306',
            ]
        ]
    ],
    'register' => [
        'handler'    => Register::class,
        'listen'     => 'text://127.0.0.1:12306',
        'count'      => 1, // must be 1
        'constructor'=> []
    ],
];
WebSocket port 8783 , Register port 12306 .

Running the service

Start the Webman application (e.g. php start.php or the command defined by the project). The service will listen on the configured ports.

Testing the connection

var ws = new WebSocket("ws://127.0.0.1:8783");

ws.onopen = function (evt) {
    console.log("Connection open ...");
    ws.send("Hello WebSockets!");
};

ws.onmessage = function (evt) {
    console.log("Received Message: " + evt.data);
    ws.close();
};

ws.onclose = function (evt) {
    console.log("Connection closed.");
};

Business logic (Events.php)

The GatewayWorker plugin forwards incoming messages to a user‑defined event class. Implement onMessage() to validate JSON and respond to the client.

/**
 * Handle a message from a client.
 *
 * @param string $clientId  Unique identifier of the client connection.
 * @param string $message  Raw message payload sent by the client.
 * @return bool  Return true to keep the connection alive.
 */
public static function onMessage(string $clientId, string $message): bool {
    $originMessage = json_decode($message, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        // Close the connection with an error payload when JSON is malformed.
        Gateway::closeClient($clientId, json_encode([
            'code' => 500,
            'msg'  => 'Invalid JSON data'
        ], JSON_UNESCAPED_UNICODE));
        return false;
    }
    // Echo the parsed data back to the client with a success code.
    return Gateway::sendToClient($clientId, json_encode([
        'code' => 200,
        'msg'  => 'Message sent successfully',
        'data' => $originMessage
    ], JSON_UNESCAPED_UNICODE));
}

Invalid data handling

When the client sends malformed JSON, the server closes the connection and returns a payload with code: 500 .

Valid data example

var ws = new WebSocket("ws://127.0.0.1:8783");

ws.onopen = function (evt) {
    console.log("Connection open ...");
    let _content = {
        "mode": 1,
        "from_username": "Tinywan",
        "to_user_id": "10000",
        "content": "Hi, 开源技术小栈"
    };
    ws.send(JSON.stringify(_content));
};

ws.onmessage = function (evt) {
    console.log("Received Message: " + evt.data);
};

ws.onclose = function (evt) {
    console.log("Connection closed.");
};
Server responds with code: 200 and echoes the submitted data.

Source code

Complete example project:

https://github.com/Tinywan/webman-admin
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

real-time messagingWebSocketPHPWebmanGatewayWorker
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.