Swoole Server getSocket

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


Latest version: pecl install openswoole-22.1.2

Declaration

<?php Swoole\Server->getSocket()

Parameters

none

Return

success

If successful, a socket resource handle is returned.

Description

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.

Examples

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.

<?php
$port = $server->listen('127.0.0.1', 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.

<?php
$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.

<?php
$server = new Swoole\Server('0.0.0.0', 9905, SWOOLE_BASE, SWOOLE_SOCK_UDP);

$server->set(
    ['worker_num' => 1]
);

$socket = $server->getSocket();

$ret = socket_set_option(
    $socket,
    IPPROTO_IP,
    MCAST_JOIN_GROUP,
    [
        'group' => '10.0.0.5', // 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));
});

$server->start();
Last updated on August 31, 2022