Listening On Multiple Ports

The swoole supports listening on multiple ports and analyzing multiple protocols.

You can set different protocols and callback functions on different ports. SSL/TLS can also enabled on certain port.

Listen on new port

<?php
$port1 = $server->listen("127.0.0.1", 9501, SWOOLE_SOCK_TCP);
$port2 = $server->listen("127.0.0.1", 9502, SWOOLE_SOCK_UDP);
$port3 = $server->listen("127.0.0.1", 9503, SWOOLE_SOCK_TCP | SWOOLE_SSL);

Set protocol

<?php
$port1->set([
    'open_length_check' => true,
    'package_length_type' => 'N',
    'package_length_offset' => 0,
    'package_max_length' => 800000,
]);

$port3->set([
    'open_eof_split' => true,
    'package_eof' => "\r\n",
    'ssl_cert_file' => 'ssl.cert',
    'ssl_key_file' => 'ssl.key',
]);

Set callback functions of events

<?php
$port1->on('connect', function ($serv, $fd){
    echo "Client:Connect.\n";
});

$port1->on('receive', function ($serv, $fd, $from_id, $data) {
    $serv->send($fd, 'Swoole: '.$data);
    $serv->close($fd);
});

$port1->on('close', function ($serv, $fd) {
    echo "Client: Close.\n";
});

$port2->on('packet', function ($serv, $data, $addr) {
    var_dump($data, $addr);
})

Optional configurations for swoole_server_port object

The swoole_server_port object can only set part of the configurations list of swoole_server

Available Configurations for swoole_server_port object:

Unavailable Configurations for swoole_server_port object:

Optional callback functions for swoole_server_port object

The swoole_server_port object can only set part of the callback functions of swoole_server

For TCP server:

For UDP server:

The below callback functions can only be setted by swoole_server object.

Q&A

The swoole_http_server class and swoole_websocket_server class inherit the swoole_server class. The swoole_server object can't call listen method to create swoole_server_port object of Http or Websocket server.

In this situation, you can create the swoole_http_server object and then call listen method to create tcp server.

<?php
$http_server=new swoole_http_server('0.0.0.0',9998); 
$http_server->set(array('xxx'=>'yyy'));
$http_server->on('request','request');
$tcp_server=$http_server->addListener('0.0.0.0',9999,SWOOLE_SOCK_TCP);