TCP/UDP Server

The TCP/UDP Server provides the API to run TCP, UDP, Unix Socket asynchronous servers. It supports IPv4, IPv6, one Way, two Way SSL and TLS Encryption. Developers do not have to know the internal implementations, you only have to write the business logic for each server event in the callback functions.

Notice: Server API can only be used in PHP CLI mode.

Methods

Events

QuickStart

Create a TCP Server

<?php
$server = new Swoole\Server("127.0.0.1", 9501, SWOOLE_BASE, SWOOLE_SOCK_TCP);

Update the settings

<?php
$server->set(array(
    'worker_num' => 4, // The number of worker processes
    'daemonize' => true, // Whether start as a daemon process
    'backlog' => 128, // TCP backlog connection number
));

Register callback functions

<?php
$server->on('connect', function() {

});
$server->on('receive', function() {

});
$server->on('close', function() {

});

There are four types of callback functions

Start the server

<?php
$server->start();

Get the server attributes

<?php
$server->manager_pid; // PID of manager process, send SIGUSR1 to this process to reload the application
$server->master_pid;  // PID of master process, send SIGTERM signal to this process to shutdown the server
$server->connections; // The connections established

Helper functions

MIME helper functions:

Since version 4.5.0

Mime Type Add

Definition:

function swoole_mime_type_add(string $suffix, string $mime_type): bool

Description:

Adds a new mime type to the built-in mime type table.

Mime Type Set

Definition:

function swoole_mime_type_set(string $suffix, string $mime_type): bool

Description:

Modify a mime type, fails if it does not exist and returns false.

Mime Type Delete

Definition:

function swoole_mime_type_delete(string $suffix): bool

Description:

Delete a mime type, fails if it does not exist and returns false.

Mime Type Get

Definition:

function swoole_mime_type_get(string $filename): string

Description:

Get the mime type corresponding to the file name.

Mime Type Exists

Definition:

function swoole_mime_type_exists(string $suffix): bool

Description:

Get whether the mime type corresponding to the suffix exists.

Getting the worker status

void Swoole\Server->getWorkerStatus (): SWOOLE_WORKER_BUSY|SWOOLE_WORKER_IDLE

Get the status of current worker process.

Since version 4.5.0

Getting the master, manger or worker process ID

void Swoole\Server->get(Master|Manager|Worker)Pid (): int

Get the PID of Master/Manager/Worker process.

Since version 4.5.0

Getting the worker ID

void Swoole\Server->getWorkerId (): int

Get the Worker ID.

Since version 4.5.0