Swoole Learning Network Communication Engine WebSocket Service

Keywords: PHP network Docker

I. Basic overview of Websocket

WebSocket protocol is a new network protocol based on TCP. It realizes full-duplex communication between browser and server - allowing server to send information to client actively.

Why do we need WebSocket?
Defect: HTTP communication can only be initiated by the client

WebSocket features:

  • Based on TCP Protocol
  • Performance overhead, low communication efficiency
  • Client can communicate with any server
  • Protocol identifier ws wss
  • Persistent Network Communication Protocol

2. Code Implementation

websocket server



//Create websocket server object and listen on port
$ws = new swoole_websocket_server("", 80);

//Listen for WebSocket Connection Open Events
$ws->on('open', function ($ws, $request) {
    var_dump($request->fd, $request->get, $request->server);
    $ws->push($request->fd, "hello, welcome\n");

//Listening for WebSocket message events
$ws->on('message', function ($ws, $frame) {
    echo "Message: {$frame->data}\n";
    $ws->push($frame->fd, "server: {$frame->data}");

//Listening for WebSocket Connection Closure Events
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";


Because we are in the docker container, we use port 80 so that we can access the service in the host browser by mapping the ports before the host passes through.

Port View of Host Container Mapping:

➜  ~ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                                        NAMES
5ee6bfcc1310        7698f               "/bin/bash"         46 hours ago        Up 30 hours>22/tcp,>80/tcp   confident_jones

Client static page

Static page path: / work/study/code/swoole/demo/static


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>WebSocket TEST</title>
    var wsUrl = "ws://";
    var websocket = new WebSocket(wsUrl);

    // Instantiating onopen objects
    websocket.onpen = function(evt){

    // Instantiate onmessage
    websocket.onmessage = function(evt){

    // Instantiate onclose
    websocket.onclose = function(evt){

    // onerror
    websocket.onerror = function (evt) {
        console.log("error:" + evt.data)



Host browser access:

Posted by wes007 on Wed, 09 Oct 2019 03:14:44 -0700