php网络编程swoole websocket

服务端:

<?php
use Swoole\WebSocket\Server;

// 创建 HTTP 服务器
$server = new Server('127.0.0.1', 8888, SWOOLE_PROCESS, SWOOLE_SOCK_TCP);

$server->on('start', function ($server) {
    //print_r($server);
    echo "Swoole websocket server is started at ws://127.0.0.1:8888\n";
});

// 设置服务器配置
$server->set([
    'worker_num' => 4,
    'log_file' => './logfile.log',
]);

// 监听 WebSocket 连接事件
$server->on('open', function (Server $server, $req) {
    echo "Connection open: {$req->fd}\n";
});

// 监听 WebSocket 消息事件
$server->on('message', function (Server $server, $frame) {
    echo "接收到客户端数据:{$frame->data}\n";
    $server->push($frame->fd, "我收到你的消息了");
});

// 监听 WebSocket 关闭事件
$server->on('close', function (Server $server, $fd) {
    echo "Connection close: {$fd}\n";
});

// 启动服务器
$server->start();

  客户端:

<?php
use Swoole\Coroutine;
use Swoole\Coroutine\Http\Client;
use function Swoole\Coroutine\run;

run(function () {
    $client = new Client('127.0.0.1', 8888);
    $ret = $client->upgrade('/');
    if ($ret) {
        $client->push('测试消息,php版本的协程客户端');
        echo "收到服务端回复:".$client->recv()."\n";
        Coroutine::sleep(0.1);
    }
});

  输出:

 

posted @ 2024-12-23 20:36  河北大学-徐小波  阅读(9)  评论(0编辑  收藏  举报