Join 4,000+ others and never miss out on new tips, tutorials, and more.
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.
$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 OpenSwoole\Constant::UNIX_DGRAM
or OpenSwoole\Constant::UNIX_STREAM
$port
is set to 0
, the OpenSwoole server will use a random and available port$sock_type
: the socket type of the server:
SSL Encryption: $sock_type | OpenSwoole\Constant::SSL
. To enable SSL, it must set using the configuration options
<?php
$server = new OpenSwoole\Server(string $host='0.0.0.0', 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("127.0.0.1", 9502, OpenSwoole\Constant::SOCK_TCP); // TCP listener
$server->addlistener("192.168.1.100", 9503, OpenSwoole\Constant::SOCK_TCP); // Web Socket listener
$server->addlistener("0.0.0.0", 9504, OpenSwoole\Constant::SOCK_UDP); // UDP listener
$server->addlistener("/var/run/myserv.sock", 0, OpenSwoole\Constant::UNIX_STREAM); // UnixSocket Stream
$server->addlistener("127.0.0.1", 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.0.0.0", 0, OpenSwoole\Constant::SOCK_TCP);
// See which port was selected
echo $port->port;