Swoole Server addListener

Declaration

<?php
Swoole\Server->addListener(string $host, int $port, string $socket_type): bool|Swoole\Server\Port

Parameters

host

The host name (IP address) to use to start the server on

port

Port number for the server to listen on

socket_type

The socket type/protocol to listen on

Return

bool|Swoole\Server\Port

If success, it returns a Swoole\Server\Port object, otherwise it returns FALSE.

Description

Add more listening IP or port for the server. The connection information can be acccessed by $server->connection_info() when the server has started. By the connection information, you can distinguish the source port of the connection.

A server can support both IPv4 and IPv6.

Alias: swoole_server->addListener(string $host, int $port, string $socket_type)

Detailed Parameter Information

  • $host: the ip address of the server

  • $port: the port of the server

    • Root privileges are required if the port is less than 1024, you will have to use sudo to start the server
    • The parameter $port will be ignored when the parameter $sock_type is set to SWOOLE_UNIX_DGRAM or SWOOLE_UNIX_STREAM
    • If the parameter $port is set to 0, the Swoole server will use a random and available port
  • $sock_type: the socket type of the server:

    • SWOOLE_SOCK_TCP: TCP
    • SWOOLE_SOCK_TCP6: TCP IPv6
    • SWOOLE_SOCK_UDP: UDP
    • SWOOLE_SOCK_UDP6: UDP IPv6
    • SWOOLE_UNIX_DGRAM: Unix socket dgram
    • SWOOLE_UNIX_STREAM: Unix socket stream
  • SSL Encryption: $sock_type | SWOOLE_SSL. To enable SSL, it must set using the configuration options

Example

<?php
$server = new Swoole\Server(string $host='0.0.0.0', int $port = 0, int $mode = SWOOLE_PROCESS, int $sockType = SWOOLE_SOCK_TCP);

// Mixing TCP and UDP listeners to monitor different ports at the same time
$server->addlistener("127.0.0.1", 9502, SWOOLE_SOCK_TCP);              // TCP listener
$server->addlistener("192.168.1.100", 9503, SWOOLE_SOCK_TCP);          // Web Socket listener
$server->addlistener("0.0.0.0", 9504, SWOOLE_SOCK_UDP);                // UDP listener
$server->addlistener("/var/run/myserv.sock", 0, SWOOLE_UNIX_STREAM);   // UnixSocket Stream
$server->addlistener("127.0.0.1", 9502, SWOOLE_SOCK_TCP | SWOOLE_SSL); //TCP + SSL

// Because port is set to 0, a random port is used
$port = $server->addListener("0.0.0.0", 0, SWOOLE_SOCK_TCP);

// See which port was selected
echo $port->port;