简体   繁体   中英

Swoole send websocket data from server to client

Hi all!

I use swoole for WebSockets.

I create clietn part:

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

Create WebServer part:

$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();

Create send from server part:

$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();

I trying to create TCP server inside WebSocket server, just adding next part inside "on start" callback:

$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();

But Just receive an error:

Swoole\\Server::__construct(): eventLoop has already been created. unable to create swoole_server.

I need to send data from server to client. How can I do this? In workerman library I doing next: https://github.com/Shkarbatov/WebSocketPHPWorkerman/blob/master/worker.php

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

You should use the addListener function instead of the new swoole_server .

the doc is here: https://www.swoole.co.uk/docs/modules/swoole-server-methods#swoole_server-addlistener

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM