kzykhys / coroutine-io
使用 *生成器* 实现的快速套接字服务器
v0.1.0
2013-11-27 10:26 UTC
Requires
- php: >=5.5.0
This package is not auto-updated.
Last update: 2024-09-10 02:08:30 UTC
README
使用 生成器 实现的快速套接字服务器。此项目深受 @nikic 的 精彩文章 的启发。
以下项目展示了 CoroutineIO 的可能性。
- kzykhys/coupe - Coupé - 使用 PURE PHP 编写的便捷 HTTP/HTTPS 服务器
需求
- PHP5.5+
安装
创建或更新你的 composer.json 文件,然后运行 composer update
{ "require": { "kzykhys/coroutine-io": "~0.1.0" } }
示例(HTTP 服务器)
- 运行
php example.php
- 在浏览器中打开
http://localhost:8000
并按住 F5 键 - 查看控制台输出
php example.php
::1:50531
GET / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:25.0) Gecko/20100101 Firefox/25.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: ja,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
example.php
<?php use CoroutineIO\Example\HttpHandler; use CoroutineIO\Example\HttpServer; require __DIR__ . '/vendor/autoload.php'; $server = new HttpServer(new HttpHandler()); $server->run();
类 HttpServer
<?php namespace CoroutineIO\Example; use CoroutineIO\Exception\Exception; use CoroutineIO\Server\Server; /** * Simple HTTP Server Implementation */ class HttpServer extends Server { /** * {@inheritdoc} */ public function createSocket($address = 'localhost:8000') { $socket = @stream_socket_server('tcp://' . $address, $no, $str); if (!$socket) { throw new Exception("$str ($no)"); } return $socket; } }
类 HttpHandler
<?php namespace CoroutineIO\Example; use CoroutineIO\Server\HandlerInterface; use CoroutineIO\Socket\ProtectedStreamSocket; use CoroutineIO\Socket\StreamSocket; /** * Simple HTTP Server Implementation */ class HttpHandler implements HandlerInterface { /** * {@inheritdoc} */ public function handleClient(StreamSocket $socket) { $socket->block(false); $data = (yield $socket->read(8048)); $response = $this->handleRequest($data, new ProtectedStreamSocket($socket)); yield $socket->write($response); yield $socket->close(); } /** * {@inheritdoc} */ public function handleRequest($input, ProtectedStreamSocket $socket) { // Displays request information echo $socket->getRemoteName() . "\n"; echo $input; return "HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-Length: 5\n\nHello"; } }
许可证
MIT 许可证
作者
Kazuyuki Hayashi (@kzykhys)