2018 swoole actual combat 2-asynchronous non blocking delivery task

Keywords: PHP

Following the last chapter Swoole battle in 2018 1 - get to know swoole

In a project, there are always scenarios that trigger behaviors that take a long time. For example, if the user updates the article and triggers the push message to all the fans of this user, if a user has 10000 fans and uses synchronized blocking method, it will surely be killed by Tucao. This scene must be implemented in a non blocking way, so that the user can not perceive.

The task delivery function of swoole can realize asynchronous non blocking function

This function is modularized by the dialogue scenario of three body person and ETO organization as follows:

Don't talk too much nonsense, light up the code

Server side

New server.php

<?php

class WebSocket {
    const HOST = '0.0.0.0';
    const PORT = 8812;
    public $ws = null;
    public function __construct()
    {
        $this->ws = new swoole_websocket_server(self::HOST, self::PORT);
        $this->ws->set(
            [
                'worker_num' => 2,
                'task_worker_num' => 2,
            ]
        );
        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('task', [$this, 'onTask']);
        $this->ws->on('finish', [$this, 'onFinish']);
        $this->ws->on('close', [$this, 'onClose']);

        $this->ws->start();
    }

    /**
     * Listening for connection events
     * @param $ws
     * @param $request
     */
    public function onOpen($ws, $request) {
        echo "Received connection request from earthman, client id: {$request->fd}\n";
    }

    /**
     * Listening for data sending events
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws, $frame) {
        echo "Data sent by earth man:{$frame->data}\n";
        echo "Fuehrer: let them clean up the waiters...\n";
        // Delivery task
        $data = [
            'task' => 'Speed up the water drop...\n',
            'fd' => $frame->fd,
        ];
        $time = date('Y-m-d H:i:s', time());
        $ws->push($frame->fd, "Clean up all the waiters, The point is not to attract anyone's attention, quietly kill Luoji!" . $time);
        $ws->task($data); // Delivery task
        $time = date('Y-m-d H:i:s', time());
        $ws->push($frame->fd, "Then there will be water drops to help you. The water drops are already speeding up. When the water drops arrive, we will have no fear... " . $time);
    }

    /**
     * Perform delivery tasks
     * @param $server
     * @param $taskId
     * @param $workerId
     * @param $data
     * @return array
     */
    public function onTask($server, $taskId, $workerId, $data) {
        echo $data['task'];
        sleep(5);
        $time = date('Y-m-d H:i:s', time());
        return [
            'fd' => $data['fd'],
            'message' => 'Droplet acceleration complete ' . $time,
        ];
    }

    /**
     * Callback after task completion
     * @date 2018-07-27
     * @param $server
     * @param $taskId
     * @param $data
     */
    public function onFinish($server, $taskId, $data) { // $data is the content returned by onTask
        $server->push($data['fd'], $data['message']); // Notify the client that the task has been completed
    }

    public function onClose($ws, $fd) {

    }

}

$obj = new WebSocket();

Client

New client.html

<!doctype html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>webSocket Client</title>
</head>
<body>
<h1>swoole Asynchronous non blocking delivery task</h1>
<script>
    let wsUrl = "ws://127.0.0.1:8812"
    console.log("ETO: Send connection request to three body world")
    let webSocket = new WebSocket(wsUrl) // Establish request connection

    webSocket.onopen = function(evt) {
        let message = "Lord, please give us the task, we will finish it!"
        console.log("ETO: " + message)
        webSocket.send(message); // Send data to the server
    }

    webSocket.onmessage = function(evt) { // Receiving server data
        let message = String(evt.data)
        console.log("Trisomy:" + message)
    }

    webSocket.onclose = function(evt) {
        console.log("The connection between the earth and the three bodies has been broken")
    }

    webSocket.onerror = function(evt, e) {
        let message = String(evt.data)
        console.log("Connection error:" + message)
    }
</script>

</body>
</html>

Startup service

☁  ws  php server.php
[2018-07-27 11:50:13 @59805.0]  TRACE   Create swoole_server host=0.0.0.0, port=8812, mode=3, type=1
client

Code parsing

Code parsing

If you think this article is helpful to you, like it or enjoy a cup of coffee money, your recognition is very important to me

Posted by makoy on Fri, 31 Jan 2020 00:42:58 -0800