WorkerMan source code analysis - implement the simplest prototype

I always thought that the workerman source code was very complicated to understand. It took 3 afternoons to study it. In fact, as long as you understand how php daemonizes processes, signals, multi-processes, and uses libevent extensions, it is easier to implement them.

The relevant code is in the github address, and there are specific comments.

Daemonization process: 
http://www.cnblogs.com/loveyouyou616/p/7867132.html
http://www.cnblogs.com/loveyouyou616/p/8881531.html
https://github.com/zhaocong222/workerman- learn/tree/master/test/daemon

signal and multi-process:
http://www.cnblogs.com/loveyouyou616/p/8854835.html
https://github.com/zhaocong222/workerman-learn/tree/master/test /signal%26%26fork

libevent extension use:
https://github.com/zhaocong222/workerman-learn/tree/master/test/libevnt

The following is the simplest prototype for workerman to read socket data
<?php
$eventBase = new EventBase();
$arr = [];

function add($fd,$func){

    global $arr,$eventBase;
    $event = new Event($eventBase, $fd, Event::READ | Event::PERSIST, $func, $fd);

    if (!$event||!$event->add()) {
        return false;
    }

    // Key point 1 
    $arr [posix_getpid()][] = $event ;
}
function baseRead($socket){
    $buffer = @fread($socket, 2);
    echo $buffer."\n";
}

function acceptConnection($socket){

    $new_socket = @stream_socket_accept($socket, 0);
    // Thundering herd.
    if (!$new_socket) {
        return;
    }

    stream_set_blocking($new_socket, 0);
    //关键点2
    stream_set_read_buffer($new_socket, 0);

    add($new_socket,'baseRead');
}

$socketmain = stream_socket_server('tcp://127.0.0.1:4455', $errno, $errmsg, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
//非阻塞
stream_set_blocking($socketmain,0);

add($socketmain,'acceptConnection');

$eventBase->loop();

focus, focus, focus

ps: I need to pay attention to 2 points here. I have been thinking about these 2 points for a long time.

1. The event instance must be stored in a global array (it should be destroyed when it leaves the function scope)

2. If the data of fwrite is larger than the size set by fread, add stream_set_read_buffer($new_socket, 0); when reading stream, it needs to be set to no buffer

To set via telnet:

The data printed by the server is as follows:

Combining signals and multi-processes through the above code is finally the core part of workerman.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326955111&siteId=291194637