Implementing a WebSocket Server and Client with Swoole in PHP

This tutorial demonstrates how to build a WebSocket server using PHP's Swoole extension and a corresponding HTML/JavaScript client, covering protocol basics, server-side event handling for connections, messages, and closures, and showing the complete code and execution results for real‑time bidirectional communication.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Implementing a WebSocket Server and Client with Swoole in PHP

In the previous lesson we installed Swoole and accessed it via HTTP; this lesson introduces the WebSocket protocol, which upgrades an HTTP connection to a persistent, bidirectional channel using the ws (or wss) scheme.

The server side is implemented in PHP using Swoole's Swoole\WebSocket\Server. A file ws_server.php creates a server listening on 0.0.0.0:9506, registers handlers for the open, message, and close events, and starts the event loop.

<?php
//创建websocket服务器对象,监听0.0.0.0:9506端口
$ws = new Swoole\WebSocket\Server("0.0.0.0", 9506);
$ws->on('open', function ($ws, $request) {
    var_dump($request->fd, $request->get, $request->server);
    $ws->push($request->fd, "hello, welcome
");
});
$ws->on('message', function ($ws, $frame) {
    echo "Message: {$frame->data}
";
    $ws->push($frame->fd, "server: {$frame->data}");
});
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed
";
});
$ws->start();
?>

The client side is a simple HTML page ws_client.html that opens a WebSocket connection to ws://0.0.0.0:9506 using the browser's WebSocket API. It defines callbacks for onopen, onmessage, onclose, and onerror to log connection status and received data.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>swoole测试websocket</title>
</head>
<body>
    <script>
        var wsServer = 'ws://0.0.0.0:9506';
        var websocket = new WebSocket(wsServer);
        websocket.onopen = function(evt) {
            console.log("Connected to WebSocket server.");
        };
        websocket.onclose = function(evt) {
            console.log("Disconnected");
        };
        websocket.onmessage = function(evt) {
            console.log('Retrieved data from server: ' + evt.data);
        };
        websocket.onerror = function(evt, e) {
            console.log('Error occured: ' + evt.data);
        };
    </script>
</body>
</html>

Running the server and opening the client page demonstrates a successful handshake, message exchange, and graceful closure, confirming that a long‑living WebSocket connection can be easily established with Swoole for real‑time applications.

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.

Backend DevelopmentWebSocketPHPSwoole
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

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.