swoole学习第五讲(创建一个websocket服务器)

开启docker9501映射端口
      ports:
        - "${WORKSPACE_SSH_PORT}:22"
        - "9501:9501"
编写webSocketServer服务ws_server.php
// 创建websocket对象
$ws = new swoole_websocket_server('0.0.0.0', 9501);

// 监听serv启动事件
$ws->on('start', function ($serv) {
    echo "Start \n";
});

// 监听websocket打开事件
$ws->on('open', function ($ws, $request) {
    var_dump($request->fd, $request->get, $request->server);
    $ws->push($request->fd, "hello, welcome \n");
});

// 监听websocket消息事件
$ws->on('message', function ($ws, $frame){
    echo "Message: $frame->data \n";
    $ws->push($frame->fd, "server: $frame->data \n");
});

// 监听webscket关闭事件
$ws->on('close', function ($ws, $fd) {
    echo "client-$fd is closed \n";
});

// 启动websocket服务器
$ws->start();
编写js客户端ws_client.html



    
    webSocket Demo





开启webSocketServer

php ws_server.php

访问websocket客户端

双击打开ws_client.html文件,在控制台查看连接情况


查看server端打印情况

你可能感兴趣的:(swoole学习第五讲(创建一个websocket服务器))