Backend Development 8 min read

Building a Simple Chatroom with WebSocket and Swoole (PHP)

This tutorial demonstrates how to create a lightweight chatroom by combining WebSocket on the front end with Swoole's WebSocket server in PHP, covering project setup, required environment, client‑side HTML/JS, server‑side PHP code, and steps to run and test the application.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Building a Simple Chatroom with WebSocket and Swoole (PHP)

Introduction – The article records a small chatroom built by integrating WebSocket with Swoole, providing a simple yet effective entry‑level example.

Project Overview – The chatroom includes a message display area, connection status indicator, a single input box, a send button (no Enter key support), auto‑scroll to the newest message, and random nicknames that disappear on page refresh.

Environment – The project is created by copying the following commands:

composer create-project topthink/think tpcd
composer require topthink/think-swoole

After installation, the front‑end page may throw a view error, which can be resolved by searching online.

Using WebSocket – The standard WebSocket API methods are used: onopen (connection established), onclose (connection closed), onmessage (message received), and onerror (error handling).

Front‑end HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>打工人聊天室</title>
    <!-- need to include jQuery -->
</head>
<style>
    .content { height:400px; max-width:400px; overflow:auto; border-radius:5px; border:1px solid #f0f0f0; }
</style>
<body>
    <div id="content" class="content"><p>聊天区域</p></div>
    你好打工人:<samp id="nickname">昵称</samp><br>
    本次连接FD: <samp id="fd-samp"></samp><br>
    <input type="text" id="msg">
    <input type="hidden" id="fd" value="">
    <button id="send" onclick="send()">发送</button>
</body>
</html>

Front‑end JavaScript – The script creates a WebSocket connection, generates a random nickname, handles sending messages, updates the UI on connection events, parses incoming JSON, distinguishes between connection‑acknowledgement (msgType 1) and chat messages (msgType 2), and auto‑scrolls the chat area.

<script>
    // Scroll to bottom
    function scrolltest(){
        var div=document.getElementById("content");
        div.scrollTop=div.scrollHeight;
    }
    var wsServer='ws://127.0.0.1:9502';
    var websocket=new WebSocket(wsServer);
    var nickname=Math.random().toString(36).substr(2);
    var thisFd='';
    $('#nickname').html(nickname);
    function send(){
        var msg=$('#msg').val();
        var data={nickname:nickname,fd:thisFd,data:msg};
        data=JSON.stringify(data);
        websocket.send(data);
        $('#msg').val('');
    }
    websocket.onopen=function(){
        $("#content >p:last-child").after('<p>服务器已连接,开始聊天吧</p>');
    };
    websocket.onclose=function(){
        $("#content >p:last-child").after('<p>服务器已断开,请重新连接</p>');
    };
    websocket.onmessage=function(evt){
        var data=eval('('+evt.data+')');
        switch(data.msgType){
            case 1:
                thisFd=data.fd;
                $('#fd-samp').html(thisFd);
                $('#fd').val(thisFd);
                break;
            case 2:
                if(data.nickname==nickname){data.nickname='我';}
                $("#content >p:last-child").after('<p>'+data.nickname+' 在 '+data.time+' 说:<br>'+data.data+'</p>');
                scrolltest();
                break;
        }
    };
    websocket.onerror=function(){
        $("#content >p:last-child").after('<p>服务器异常</p>');
    };
&lt;/script&gt;

Server‑side PHP (Swoole) – The server creates a WebSocket listener on port 9502, sends an initial acknowledgement containing the client’s FD, processes incoming messages by adding a timestamp and msgType, and broadcasts the message to all connected clients.

&lt;?php
    $ws = new Swoole\WebSocket\Server('0.0.0.0', 9502);
    $ws->on('open', function($ws, $request){
        $fd = $request->fd;
        $data = json_encode(['fd'=>$fd,'msgType'=>1]);
        $ws->push($request->fd, $data);
    });
    $ws->on('message', function($ws, $frame){
        $data = json_decode($frame->data);
        $data->msgType = 2;
        $data->time = date('Y-m-d H-i-s');
        $data = json_encode($data);
        foreach($ws->connections as $conn_fd){
            $ws->push($conn_fd, $data);
        }
    });
    $ws->on('close', function($ws, $fd){ /* client closed */ });
    $ws->start();
?>

Running the Application – After the code is complete, start the PHP file from the console, open the front‑end page (e.g., http://127.0.0.1 ) in a browser, open multiple windows to simulate different users, and test sending messages.

Conclusion – Although the code is simple, it clearly demonstrates the power of combining WebSocket with Swoole for real‑time communication.

frontendJavaScriptWebSocketSwoolechatroom
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login 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.