大家好!
我对WebSocket使用swoole。
我创建了客户端部分:
<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。
我需要将数据从服务器发送到客户端。我怎样才能做到这一点? 接下来,在工人图书馆中: https://github.com/Shkarbatov/WebSocketPHPWorkerman/blob/master/worker.php
答案 0 :(得分:0)
在github上上传工作结果:https://github.com/Shkarbatov/WebSocketPHPSwoole
答案 1 :(得分:0)
您应该使用addListener
函数而不是new swoole_server
。
文档在这里:
https://www.swoole.co.uk/docs/modules/swoole-server-methods#swoole_server-addlistener