Swoole Server getSocket

4.x is outdated, please check the latest version 22.x

Latest version: pecl install openswoole-22.1.2


<?php Swoole\Server->getSocket()





If successful, a socket resource handle is returned.


Get a socket resource handle and update the options of the socket.

This method is based on the PHP socket extension and it needs to be compiled with the --enable-sockets configuration when installing Swoole.


There are multiple ways to use the socket resource.

Socket Resource from Listening Port

Using the listen method of returned port, you can use Swoole\Server\Port object to get a socket resource/handler.

$port = $server->listen('', 9502, SWOOLE_SOCK_TCP);
$socket = $port->getSocket();

Socket Option Setting Example

Using the socket_set_option function to set the number of lower-level socket parameters.

$socket = $server->getSocket();

if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1))
    echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;

Multi Cast Example

Use socket_set_option and MCAST_JOIN_GROUP parameters to add a socket to a multicast network to monitor packets.

$server = new Swoole\Server('', 9905, SWOOLE_BASE, SWOOLE_SOCK_UDP);

    ['worker_num' => 1]

$socket = $server->getSocket();

$ret = socket_set_option(
        'group' => '', // Represents a multicast address
        'interface' => 'eth0', // Indicates the name of the network interface, which can be a number or a string, such as eth0, wlan0

if ($ret === false)
    throw new RuntimeException('Unable to join the multicast group');

$server->on('Packet', function (Swoole\Server $serv, $data, $addr)
    $serv->sendto($addr['address'], $addr['port'], "Swoole: $data");
    var_dump( $addr, strlen($data));

Last updated on August 31, 2022