大网数据广告活动
PHP 语言与运行手册

EventHttp::accept · Makes an HTTP server accept connections on the specified socket stream or resource

· 52CE 我爱测

EventHttp::accept — Makes an HTTP server accept connections on the specified socket stream or resource

EventHttp::accept

(PECL event >= 1.2.6-beta)

EventHttp::accept — Makes an HTTP server accept connections on the specified socket stream or resource

说明

public function EventHttp::accept( mixed $socket ): bool

Makes an HTTP server accept connections on the specified socket stream or resource. The socket should be ready to accept connections.

Can be called multiple times to accept connections on different sockets.

注意:

To bind a socket, listen, and accept connections on the socket in a single call use EventHttp::bind(). EventHttp::accept() is needed only if one already has a socket ready to accept connections.

参数

socket

Socket resource, stream or numeric file descriptor representing a socket ready to accept connections.

返回值

成功时返回 true, 或者在失败时返回 false。

示例

示例 #1 EventHttp::accept() example

<?php

$base = new EventBase();
$http = new EventHttp($base);

$addresses = [
    8091 => "127.0.0.1",
    8092 => "127.0.0.2",
];
$i = 0;

$socket = array();

foreach ($addresses as $port => $ip) {
    echo $ip, " ", $port, PHP_EOL;
    $socket[$i] = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

    if (!socket_bind($socket[$i], $ip, $port)) {
        exit("socket_bind failed\n");
    }

    socket_listen($socket[$i], 0);
    socket_set_nonblock($socket[$i]);

    if (!$http->accept($socket[$i])) {
        echo "Accept failed\n";
        exit(1);
    }

    ++$i;
}

$http->setCallback("/some-page", function () {
    echo "(some-page)\n";
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
    echo "OK\n";
});

$http->setDefaultCallback(function ($req) {
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
    echo "OK\n";
});

$signal = Event::signal($base, SIGINT, function () use ($base) {
    echo "Caught SIGINT. Stopping...\n";
    $base->stop();
});
$signal->add();

$base->dispatch();
echo "END\n";
// We didn't close sockets, since Libevent already sets
// CLOSE_ON_FREE and CLOSE_ON_EXEC flags on the file 
// descriptor associated with the sockets.
?>

以上示例的输出类似于:

Client:
$ nc 127.0.0.1 8091
GET /about HTTP/1.0
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

Server:
127.0.0.1 8091
127.0.0.2 8092
URI: /about
OK

参见

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。