目前情況:用GatewayWorker創(chuàng)建tcp服務(wù)器A能和設(shè)備保持長連接,能接收設(shè)備的數(shù)據(jù),也能發(fā)送數(shù)據(jù)給設(shè)備
想要實現(xiàn):用GatewayWorker創(chuàng)建tcp服務(wù)器A,我想把設(shè)備端傳遞過來的數(shù)據(jù)轉(zhuǎn)發(fā)到另外一個tcp服務(wù)器B,并和tcp服務(wù)器B保持長連接,接收tcp服務(wù)器B數(shù)據(jù),通過tcp服務(wù)器A發(fā)送給設(shè)備
沒找到適合的方案
找到的方案:
<?php
namespace App\GatewayWorker;
use GatewayWorker\Lib\Gateway;
use Illuminate\Support\Facades\Log;
class Events
{
//tcpB服務(wù)器連接
private static $tcpServerConnection = null;
public static function onWorkerStart($businessWorker){
Log::info('tcpA:啟動服務(wù)');
// 建立與目標(biāo)tcpB服務(wù)器的連接
self::$tcpServerConnection = new \Workerman\Connection\TcpConnection(stream_socket_client('tcpB'));
// tcpB處理連接成功回調(diào)
self::$tcpServerConnection->onConnect = function ($tcpServerConnection) {
Log::info('tcpB服務(wù)器:連接到目標(biāo)TCPb服務(wù)器成功');
};
// tcpB處理接收到的數(shù)據(jù)回調(diào)
self::$tcpServerConnection->onMessage = function ($tcpServerConnection, $tcpServerData) {
// 將從目標(biāo)TCP服務(wù)器接收到的數(shù)據(jù)轉(zhuǎn)發(fā)給設(shè)備
Gateway::sendToAll($tcpServerData);
Log::info('tcpB服務(wù)器:接收到目標(biāo)TCb服務(wù)器的數(shù)據(jù)-' . $tcpServerData);
};
// tcpB處理連接關(guān)閉回調(diào)
self::$tcpServerConnection->onClose = function ($tcpServerConnection) {
Log::info('tcpB服務(wù)器:與目標(biāo)TCPb服務(wù)器的連接已關(guān)閉');
};
}
public static function onConnect($client_id){
Log::info('tcpA:連接成功-' . $client_id);
}
public static function onWebSocketConnect($client_id, $data){
Log::info('tcpA:onWebSocketConnect' . $client_id);
}
public static function onMessage($client_id, $message){
Log::info('tcpA:收到消息-' .$message.'-'. $client_id);
// 將接收到的數(shù)據(jù)轉(zhuǎn)發(fā)給目標(biāo)TCPb服務(wù)器
if (self::$tcpServerConnection !== null) {
self::$tcpServerConnection->send($message);
Log::info('tcpB:轉(zhuǎn)發(fā)數(shù)據(jù)給目標(biāo)TCPb服務(wù)器-' . $message);
} else {
Log::info('tcpB:目標(biāo)TCPb服務(wù)器連接未建立,無法轉(zhuǎn)發(fā)數(shù)據(jù)');
}
}
public static function onClose($client_id){
Log::info('tcpA:斷開連接-' . $client_id);
}
}
如果有更好的方法,大家一起討論