TCP和websocket通讯

所用技术

  1. PHP环境
  2. workerman

实现原理

代码

<?php
use Workerman\Worker;

require_once __DIR__ . '/vendor/autoload.php';

$websocket = new Worker('Websocket://0.0.0.0:8888');
$websocket->count = 1;
$websocket->onWorkerStart = function ($websocket) {
    // 启动第一个tcp进程
    $tcp1 = new Worker('tcp://0.0.0.0:6000');
    // 设置到socketArray属性上
    $websocket->tcpArray[] = $tcp1;
    $tcp1->listen();

    // 启动第二个tcp
    $tcp2 = new Worker('tcp://0.0.0.0:6001');
    $websocket->tcpArray[] = $tcp2;
    $tcp2->listen();
};

// 接受websocket消息后转发给tcp
$websocket->onMessage = function ($conn, $data) {
    global $websocket;

    foreach($websocket->tcpArray as $tcpItem)
    {
        foreach ($tcpItem->connections as $tcpConn) {
            $tcpConn->send($data);
        }
    }
};

Worker::runAll();

03-05 23:26