Basic Process

(Taking a simple Websocket chat server as an example)

1. Create a project directory anywhere

For example, SimpleChat/
Enter the directory and run composer require workerman/workerman

2. Include vendor/autoload.php (generated after composer installation)

Create start.php and include vendor/autoload.php

use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

3. Select a protocol

Here we choose the Text protocol (a custom protocol in Workerman, formatted as text + newline)

(Currently, Workerman supports HTTP, Websocket, and Text protocols. If you need to use other protocols, please refer to the protocol chapter to develop your own.)

4. Write an entry point startup script as needed

For example, the following is a simple chat entry file.

SimpleChat/start.php

<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

$global_uid = 0;

// Allocate uid when a client connects, save the connection, and notify all clients
function handle_connection($connection)
{
    global $text_worker, $global_uid;
    // Assign a uid to this connection
    $connection->uid = ++$global_uid;
}

// When a client sends a message, forward it to everyone
function handle_message(TcpConnection $connection, $data)
{
    global $text_worker;
    foreach($text_worker->connections as $conn)
    {
        $conn->send("user[{$connection->uid}] said: $data");
    }
}

// When a client disconnects, broadcast to all clients
function handle_close($connection)
{
    global $text_worker;
    foreach($text_worker->connections as $conn)
    {
        $conn->send("user[{$connection->uid}] logout");
    }
}

// Create a Worker for the text protocol listening on port 2347
$text_worker = new Worker("text://0.0.0.0:2347");

// Only start 1 process, making it easier for data transmission between clients
$text_worker->count = 1;

$text_worker->onConnect = 'handle_connection';
$text_worker->onMessage = 'handle_message';
$text_worker->onClose = 'handle_close';

Worker::runAll();

5. Testing

The Text protocol can be tested using the telnet command

telnet 127.0.0.1 2347