GatewayWorker怎么做中转服务器

liong

问题描述

目前情况:用GatewayWorker创建tcp服务器A能和设备保持长连接,能接收设备的数据,也能发送数据给设备

想要实现:用GatewayWorker创建tcp服务器A,我想把设备端传递过来的数据转发到另外一个tcp服务器B,并和tcp服务器B保持长连接,接收tcp服务器B数据,通过tcp服务器A发送给设备

为此你搜索到了哪些方案及不适用的原因

没找到适合的方案

找到的方案:

<?php

namespace App\GatewayWorker;
use GatewayWorker\Lib\Gateway;
use Illuminate\Support\Facades\Log;

class Events
{
    //tcpB服务器连接
    private static $tcpServerConnection = null;
    public static function onWorkerStart($businessWorker){
        Log::info('tcpA:启动服务');
        // 建立与目标tcpB服务器的连接
        self::$tcpServerConnection = new \Workerman\Connection\TcpConnection(stream_socket_client('tcpB'));
        // tcpB处理连接成功回调
        self::$tcpServerConnection->onConnect = function ($tcpServerConnection) {
            Log::info('tcpB服务器:连接到目标TCPb服务器成功');
        };
        // tcpB处理接收到的数据回调
        self::$tcpServerConnection->onMessage = function ($tcpServerConnection, $tcpServerData) {
            // 将从目标TCP服务器接收到的数据转发给设备
            Gateway::sendToAll($tcpServerData);
            Log::info('tcpB服务器:接收到目标TCb服务器的数据-' . $tcpServerData);
        };
        // tcpB处理连接关闭回调
        self::$tcpServerConnection->onClose = function ($tcpServerConnection) {
            Log::info('tcpB服务器:与目标TCPb服务器的连接已关闭');
        };
    }
    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);

        // 将接收到的数据转发给目标TCPb服务器
        if (self::$tcpServerConnection !== null) {
            self::$tcpServerConnection->send($message);
            Log::info('tcpB:转发数据给目标TCPb服务器-' . $message);
        } else {
            Log::info('tcpB:目标TCPb服务器连接未建立,无法转发数据');
        }
    }

    public static function onClose($client_id){
        Log::info('tcpA:断开连接-' . $client_id);
    }

}

如果有更好的方法,大家一起讨论

411 1 1
1个回答

软饭工程师

既然这样,为什么不在A 服务器装个nginx 呢

🔝