Example of using web sockets in php with workerman

Please provide an example of using the workerman library. The whole Internet is littered with examples of the helloworld type, which I can already reproduce from memory a dozen myself, but they are useless for solving practical problems. There is a great lack of theory on application.

I can't find any documentation or articles (except for the primitive ones), I have already read the Japanese or Chinese original with Google translate, downloaded the source code (again with hieroglyphs in the comments), offered by the author. But it is very difficult to understand the concept, the essence of the library. Perhaps it is worth studying the sockets themselves more deeply, this answer will also suit me, but I will ask again with specifics, what exactly and where to read.

The task is quite simple: the client connects to the server, tells it what information it needs, and starts waiting for messages. The front part is clear, but how to send a message to the client on the backend is not clear. Where and what to initiate so that the dataset X is destined to the client Y, got to him.

Author: kuramp, 2018-07-05

1 answers

Sending a message to a specific user

Server

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

// массив для связи соединения пользователя и необходимого нам параметра
$users = [];

// создаём ws-сервер, к которому будут подключаться все наши пользователи
$ws_worker = new Worker("websocket://0.0.0.0:8000");
// создаём обработчик, который будет выполняться при запуске ws-сервера
$ws_worker->onWorkerStart = function() use (&$users)
{
    // создаём локальный tcp-сервер, чтобы отправлять на него сообщения из кода нашего сайта
    $inner_tcp_worker = new Worker("tcp://127.0.0.1:1234");
    // создаём обработчик сообщений, который будет срабатывать,
    // когда на локальный tcp-сокет приходит сообщение
    $inner_tcp_worker->onMessage = function($connection, $data) use (&$users) {
        $data = json_decode($data);
        // отправляем сообщение пользователю по userId
        if (isset($users[$data->user])) {
            $webconnection = $users[$data->user];
            $webconnection->send($data->message);
        }
    };
    $inner_tcp_worker->listen();
};

$ws_worker->onConnect = function($connection) use (&$users)
{
    $connection->onWebSocketConnect = function($connection) use (&$users)
    {
        // при подключении нового пользователя сохраняем get-параметр, который же сами и передали со страницы сайта
        $users[$_GET['user']] = $connection;
        // вместо get-параметра можно также использовать параметр из cookie, например $_COOKIE['PHPSESSID']
    };
};

$ws_worker->onClose = function($connection) use(&$users)
{
    // удаляем параметр при отключении пользователя
    $user = array_search($connection, $users);
    unset($users[$user]);
};

// Run worker
Worker::runAll();

Client

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <script>
        ws = new WebSocket("ws://127.0.0.1:8000/?user=tester01");
        ws.onmessage = function(evt) {alert(evt.data);};
    </script>
</head>
</html>

Sending a message

<?php
$localsocket = 'tcp://127.0.0.1:1234';
$user = 'tester01';
$message = 'test';

// соединяемся с локальным tcp-сервером
$instance = stream_socket_client($localsocket);
// отправляем сообщение
fwrite($instance, json_encode(['user' => $user, 'message' => $message])  . "\n");
 8
Author: madfan41k, 2018-07-05 14:01:25