6

我可以使用 libevent 制作一个简单的 php websocket 服务器,但是当我尝试使其成为多处理时我被卡住了。

例如这是单一处理

<?php
$socket = stream_socket_server ('tcp://0.0.0.0:2000', $errno, $errstr);
stream_set_blocking($socket, 0);
$base = event_base_new();
$event = event_new();
event_set($event, $socket, EV_READ | EV_PERSIST, 'ev_accept', $base);
event_base_set($event, $base);
event_add($event);
event_base_loop($base);

$GLOBALS['connections'] = array();
$GLOBALS['buffers'] = array();

function ev_accept($socket, $flag, $base) {
    static $id = 0;

    $connection = stream_socket_accept($socket);
    stream_set_blocking($connection, 0);

    $id += 1;

    $buffer = event_buffer_new($connection, 'ev_read', NULL, 'ev_error', $id);
    event_buffer_base_set($buffer, $base);
    event_buffer_timeout_set($buffer, 30, 30);
    event_buffer_watermark_set($buffer, EV_READ, 0, 0xffffff);
    event_buffer_priority_set($buffer, 10);
    event_buffer_enable($buffer, EV_READ | EV_PERSIST);

    // we need to save both buffer and connection outside
    $GLOBALS['connections'][$id] = $connection;
    $GLOBALS['buffers'][$id] = $buffer;
}

function ev_error($buffer, $error, $id) {
    event_buffer_disable($GLOBALS['buffers'][$id], EV_READ | EV_WRITE);
    event_buffer_free($GLOBALS['buffers'][$id]);
    fclose($GLOBALS['connections'][$id]);
    unset($GLOBALS['buffers'][$id], $GLOBALS['connections'][$id]);
}

function ev_read($buffer, $id) {
    while ($read = event_buffer_read($buffer, 256)) {
        var_dump($read);
    }
}
?> 

但是当我在函数 ev_read 中这样做时

     function ev_read($buffer, $id) {
            while ($read = event_buffer_read($buffer, 256)) {
    $pid = pcntl_fork();
        switch ($pid) {
        case -1: // Error
            die('Fork failed, your system is b0rked!');
            break;
        case 0: // Child
                event_buffer_write($buffer,"asdawdasd");

        exit(0);
            break;


            }
   } }

它不发送数据...

那么如何制作一个多处理 php 套接字服务器呢?

4

1 回答 1

5

虽然 nanoserv 是一个优秀的库,但它不使用 libevent。事实上,作者本人在他的博客中写道,他想在某个时间点将 nanoserv 转换为使用 libevent。在这里查看他的博客文章:http: //blog.si.kz/index.php/2010/02/03/libevent-for-php

Alix Axel 在 2011 年 5 月 22 日 12:19 也对此发表了评论。

更新:更多的研究让我找到了http://phpdaemon.net/。似乎他们正在使用 libevent 来构建整个网络服务器主机

2021 年 5 月 30 日更新:最近有https://www.swoole.co.uk/https://reactphp.org/为套接字提供了良好的异步库。

phpdaemon 在https://daemon.io/有一个新的 url

于 2012-10-18T18:07:24.363 回答