我要做的是:
(套接字服务器:9006(<-(Websocket客户端(->(:8080 Websocket服务器(
我想从Socket Server读取数据,编辑一些内容,然后发送到Websocket服务器。我必须能够在同一时间读取来自Websocker服务器的数据
我成功地使用1个用于Socket服务器的React连接器和1个用于WebSocket服务器的Ratchet连接器连接到了这两个服务器:
$loop = ReactEventLoopFactory::create();
$connector = new ReactSocketConnector($loop);
$connector->connect('192.168.0.1:9006')->then(function (ReactSocketConnectionInterface $connection) use ($loop) {
$connection->pipe(new ReactStreamWritableResourceStream(STDOUT, $loop));
$connection->write("Hello World!n");
$connection->on('data', function ($chunk) {
echo $chunk;
// How to send $chunk to the Websocket server through second connector, see below?
});
});
$reactConnector = new ReactSocketConnector($loop, [
'dns' => '8.8.8.8',
'timeout' => 10
]);
$connector = new RatchetClientConnector($loop, $reactConnector);
$connector('ws://1.2.3.4:8080')
->then(function(RatchetClientWebSocket $conn) {
$conn->on('message', function(RatchetRFC6455MessagingMessageInterface $msg) use ($conn) {
echo "Received: {$msg}n";
// $conn->close();
});
$conn->on('close', function($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})n";
});
$conn->send('Hello World!');
}, function(Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}n";
$loop->stop();
});
$loop->run();
所以我的问题是:如何使用在第一个连接器和第二个连接器中接收到的数据?
谢谢你的帮助!
我找到了解决方案,如果它能帮助任何人,我就贴在那里…:
require __DIR__ . '/vendor/autoload.php';
use ReactSocketConnector;
use ReactSocketConnectionInterface;
$loop = ReactEventLoopFactory::create();
$reactConnector = new ReactSocketConnector($loop, [
'dns' => '8.8.8.8',
'timeout' => 10
]);
$wsConnector = new RatchetClientConnector($loop, $reactConnector);
$wsConnector('ws://1.2.3.4:8080')
->then(function(RatchetClientWebSocket $wsConn) use ($loop) {
$socketConnector = new ReactSocketConnector($loop);
$socketConnector->connect('192.168.0.1:9006')->then(function (ConnectionInterface $socketConn) use ($wsConn) {
$socketConn->on('data', function ($msg) use ($wsConn){
printf("Msg received from Socket Server : %sn", $msg);
// Send it to wsServer
$wsConn->send($msg);
});
});
$wsConn->on('message', function(RatchetRFC6455MessagingMessageInterface $msg) use ($wsConn) {
printf("Msg received from WebSocket Server : %sn", $msg);
});
$wsConn->on('close', function($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})n";
});
}, function(Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}n";
$loop->stop();
});
$loop->run();