OpenSwoole Server getSocket

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

Declaration

<?php OpenSwoole\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 OpenSwoole\Server\Port object to get a socket resource/handler.

<?php
$port = $server->listen('127.0.0.1', 9502, OpenSwoole\Constant::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 OpenSwoole\Server('0.0.0.0', 9905, OpenSwoole\Server::SIMPLE_MODE, OpenSwoole\Constant::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 (OpenSwoole\Server $serv, $data, $addr)
{
    $serv->sendto($addr['address'], $addr['port'], "OpenSwoole: $data");
    var_dump( $addr, strlen($data));
});

$server->start();
Last updated on September 20, 2022