OpenSwoole Server addListener

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5


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



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


Port number for the server to listen on


The socket type/protocol to listen on



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


Add more listening IP or port for the server. The connection information can be acccessed by $server->getClientInfo() 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.

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 OpenSwoole\Constant::UNIX_DGRAM or OpenSwoole\Constant::UNIX_STREAM
    • If the parameter $port is set to 0, the OpenSwoole server will use a random and available port
  • $sock_type: the socket type of the server:

    • OpenSwoole\Constant::SOCK_TCP: TCP
    • OpenSwoole\Constant::SOCK_TCP6: TCP IPv6
    • OpenSwoole\Constant::SOCK_UDP: UDP
    • OpenSwoole\Constant::SOCK_UDP6: UDP IPv6
    • OpenSwoole\Constant::UNIX_DGRAM: Unix socket dgram
    • OpenSwoole\Constant::UNIX_STREAM: Unix socket stream
  • SSL Encryption: $sock_type | OpenSwoole\Constant::SSL. To enable SSL, it must set using the configuration options


$server = new OpenSwoole\Server(string $host='', int $port = 0, int $mode = OpenSwoole\Server::POOL_MODE, int $sockType = OpenSwoole\Constant::SOCK_TCP);

// Mixing TCP and UDP listeners to monitor different ports at the same time
$server->addlistener("", 9502, OpenSwoole\Constant::SOCK_TCP);              // TCP listener
$server->addlistener("", 9503, OpenSwoole\Constant::SOCK_TCP);          // Web Socket listener
$server->addlistener("", 9504, OpenSwoole\Constant::SOCK_UDP);                // UDP listener
$server->addlistener("/var/run/myserv.sock", 0, OpenSwoole\Constant::UNIX_STREAM);   // UnixSocket Stream
$server->addlistener("", 9502, OpenSwoole\Constant::SOCK_TCP | OpenSwoole\Constant::SSL); //TCP + SSL

// Because port is set to 0, a random port is used
$port = $server->addListener("", 0, OpenSwoole\Constant::SOCK_TCP);

// See which port was selected
echo $port->port;
Last updated on September 20, 2022