walkor / phpsocket.io

A server side alternative implementation of socket.io in PHP based on workerman.
2.3k stars 508 forks source link

Use two protocols on different ports with the same worker #268

Closed marcosmarcolin closed 3 years ago

marcosmarcolin commented 3 years ago

Hi, all right?

Ex: I have the following situation, I need to have a worker on port 2021 with https, and another on port 2020 with http. Besides sharing the same event-loops, that is, I don't want to duplicate the events, since they are the same for both, it just changes the way the connection is made.

In NodeJS it behaves as follows:

var io = require('socket.io')();

var server = require('https').createServer({key:fs.readFileSync('/cert.key'), cert:fs.readFileSync('/cert.crt')}, app);
io.attach(server);
server.listen(2021,function(){
    //console.log('listando na porta 2021');
});

var server2 = require('http').createServer(app);
io.attach(server2);
server2.listen(2020,function(){
    //console.log('listando na porta 2021');
});

So, regardless of the way they connect, they share the use of the same events.

Can I reproduce this with this package? I took a look at workerman/channel, but I didn't see another way without duplicating it.

Thanks for listening.

walkor commented 3 years ago

I think add a ssl proxy is an easy way. The ssl proxy can be nginx or workerman. For ssl proxy of workerman the codes may like this.


<?php
use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
use PHPSocketIO\SocketIO;

// 2020 for http
$io = new SocketIO(2020);
$io->.....

// 2021 proxy for https
$context = array(
    'ssl' => array(
        'local_cert'  => '/etc/nginx/conf.d/ssl/server.pem', 
        'local_pk'    => '/etc/nginx/conf.d/ssl/server.key',
        'verify_peer' => false,
    )
);
$worker = new Worker('tcp://0.0.0.0:2021', $context);
$worker->transport = 'ssl';
$worker->onConnect = function($connection)
{
    $connection_to_socketio = new AsyncTcpConnection('tcp://127.0.0.1:2020');
    $connection->pipe($connection_to_socketio);
    $connection_to_socketio->pipe($connection);
    $connection_to_socketio->connect();
};

Worker::runAll();