Join 4,000+ others and never miss out on new tips, tutorials, and more.
4.x is outdated, please check the latest version 22.x
Latest version:
pecl install openswoole-22.1.2
<?php Swoole\Server->addListener(string $host, int $port, string $socket_type): bool|Swoole\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 Swoole\Server\Port
object, otherwise it returns FALSE.
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)
$host
: the ip address of the server
$port
: the port of the server
$port
will be ignored when the parameter $sock_type
is set to SWOOLE_UNIX_DGRAM
or SWOOLE_UNIX_STREAM
$port
is set to 0
, the Swoole server will use a random and available port$sock_type
: the socket type of the server:
SSL Encryption: $sock_type | SWOOLE_SSL
. To enable SSL, it must set using the configuration options
<?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;