0

大家好!

我将 swoole 用于 WebSockets。

我创建客户端部分:

<script>
    var ws = new WebSocket('ws://site.ll:9502/?user=tester01');
    ws.onmessage = function(evt) { console.log(evt.data); };

    ws.onopen = function (event) {
        ws.send('test');
    }
</script>

创建 WebServer 部分:

$server = new swoole_websocket_server("127.0.0.1", 9502);

$server->on("start", function ($server) {
    echo "Swoole http server is started at http://127.0.0.1:9502\n";
});

$server->on('open', function($server, $req) {
    echo "connection open: {$req->fd}\n";
});

$server->on('message', function($server, $frame) {
    echo "received message: {$frame->data}\n";
    $server->push($frame->fd, json_encode(["hello", "world"]));
});

$server->on('close', function($server, $fd) {
    echo "connection close: {$fd}\n";
});

$server->start();

从服务器部分创建发送:

$client = new swoole_client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9502, -1)) {
    exit("connect failed. Error: {$client->errCode}\n");
}
$client->send("hello world\n");
echo $client->recv();
$client->close();

我试图在 WebSocket 服务器中创建 TCP 服务器,只需在“启动”回调中添加下一部分:

$server2 = new swoole_server("127.0.0.1", 9503);
$server2->on('connect', function ($server2, $fd){
    echo "connection open: {$fd}\n";
});
$server2->on('receive', function ($server2, $fd, $from_id, $data) {
    $server2->send($fd, "Swoole: {$data}");
    $server2->close($fd);
});
$server2->on('close', function ($server2, $fd) {
    echo "connection close: {$fd}\n";
});
$server2->start();

但只是收到一个错误:

Swoole\Server::__construct(): eventLoop 已经创建。无法创建 swoole_server。

我需要将数据从服务器发送到客户端。我怎样才能做到这一点?在workerman库中,我接下来要做: https ://github.com/Shkarbatov/WebSocketPHPWorkerman/blob/master/worker.php

4

2 回答 2

0

在 github 上上传工作结果:https ://github.com/Shkarbatov/WebSocketPHPSwoole

于 2018-08-22T10:37:49.967 回答
0

您应该使用该addListener函数而不是new swoole_server.

文档在这里: https://www.swoole.co.uk/docs/modules/swoole-server-methods#swoole_server-addlistener

于 2018-11-23T07:08:47.320 回答