icicleio / http Goto Github PK
View Code? Open in Web Editor NEWHTTP component for Icicle
License: MIT License
HTTP component for Icicle
License: MIT License
I use apache jemeter to make benchmark on the example server(with litter modify):
public function onRequest(Request $request, Socket $socket)
{
$data = sprintf(
'Hello to %s:%d from %s:%d!',
$socket->getRemoteAddress(),
$socket->getRemotePort(),
$socket->getLocalAddress(),
$socket->getLocalPort()
);
$body = $request->getBody();
if ($body->isReadable()) {
$data .= "\n\n";
do {
$data .= (yield $body->read());
} while ($body->isReadable());
}
$coroutine = Coroutine\create(function () {
$client = new Client();
$encoder = new Http1Encoder();
// Connect to a google.com IP.
// Use Icicle\Dns\connect() in icicleio/dns package to resolve and connect using domain names.
$data = '';
//Make a http request to another site
try {
$socket = (yield Icicle\Socket\connect('10.123.5.34', 80));
/** @var \Icicle\Http\Message\Response $response */
$response = (yield $client->request($socket, 'GET', 'an url', ['Cookie' => 'cookie=xxx']));
$stream = $response->getBody();
while ($stream->isReadable()) {
$data .= (yield $stream->read());
}
} catch (\Exception $e) {
echo "Catch Exception by me : " . $e->getMessage() . "\n";
}
yield $data;
});
$coroutine->done(null, function (Exception $exception) {
printf("Exception: %s\n", $exception);
});
$data .= (yield $coroutine);
$sink = new MemorySink();
yield $sink->end($data);
$response = new BasicResponse(200, [
'Content-Type' => 'text/plain',
'Content-Length' => $sink->getLength(),
], $sink);
yield $response;
}
I found the memory use by the process is increase, and not decrease:
~/dev/icicle ยป ps -e -o 'pid,ppid,rsz,vsz,args' | grep php
114552 7223 125376 411320 php server.php
And there have many error output like:
Error when handling request from 192.168.103.1:51302: Failed to write to stream. Errno: 2; fwrite(): 2588 is not a valid stream resource
If I continue benchmark, will suffer a fatal error:
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted at /home/rokety/software/php-5.6.15/Zend/zend_execute.h:187 (tried to allocate 130968 bytes) in /home/rokety/dev/icicle/vendor/icicleio/http/src/Driver/Encoder/Http1Encoder.php on line 70
Another, If I ctrl+c
the server script, it print a memory leak message:
/home/rokety/software/php-5.6.15/Zend/zend_vm_execute.h(944) : Freeing 0x7F8E06527168 (32 bytes), script=/home/rokety/dev/icicle/server.php
=== Total 1 memory leaks detected ===
Will http persistent connection feature be implemented in the near future? Thanks.
How can I get the POST data into a string in the onRequest
method? I've tried a bunch of things but I simply can't figure it out. Preferably I just want to block until the body is read, I don't need any kind of concurrency in this case.
I was wondering if it is possible to stream a chunked response using icicle.
Could someone please provide a small example of how I would write to the response's output stream line by line.
If I have this generator:
function getFileLines($file, $mode) {
$f = fopen($file, $mode);
try {
while ($line = fgets($f)) {
yield $line;
}
} finally {
fclose($f);
}
}
``
then I would like to be able to send each line to the client using chunked transfer encoding
// Create some kind of response stream here ???
$responseStream = ...
$mime = 'application/json';
$response = new BasicResponse(200, [
'Content-Type' => $mime,
'Connection' => 'keep-alive',
'Transfer-Encoding' => 'chunked',
'Server' => PROD.'/'.WS_VERSION,
'Date' => gmdate('D, d M Y H:i:s T')
], $responseStream);
$responseStream->seek(0);
$pos = 0;
foreach(getFileLines('some/file.txt') as $l) {
$len = dechex(strlen($l));
$line = $len."\r\n";
$line.= $l."\r\n"
$responseStream->write($line);
$pos+= strlen($line);
$responseStream->seek($pos);
}
// End the chunked transfer
$responseStream->end("00\r\n\r\n");
How can I achieve this using ICICLEIO ?
Thanks in advance
Looks like this library comes with it's own implementation of HTTP messages, almost identical to those defined in PSR-7 standard, but not compatible on interface level. I can see that:
UriInterface
can be used directlyRequestInterface
and ResponseInterface
are almost compatibleI think it is worth to build building some kind of bridge between this implementations, for the sake of compatibility. It won't be very elegant if you think about good OOP practices, but it's going to be very pragmatic - say someone develops PSR-7 library for detecting mobile devices using headers, it could be used directly from within icicle/http
app.
This "bridge" can be implemented in many different ways. As an example, Request class could have following methods:
public function getBody()
{
throw new RuntimeException("Synchronous stream is not supported");
}
public function getAsyncBody() // ...or whatever name would be better
{
return $this->stream;
}
You get incompatible getBody(), but everything else (headers, uri) can be used as always.
What do you think? I could create a PR with example bridge implementation.
Hi Aaron,
I'm playing around with building simple WebSocket implementation over icicle libs - for fun and learning purposes.
I was able to easily hack something around base icicle
library, but interacting with icicle/http
is a different story. I can complete the handshake and send headers back, but after that I'm not able to read input anymore. Here's what I'm trying to do:
class WebSocketMiddleware
{
public function __invoke(RequestInterface $request, ClientInterface $client)
{
echo "Handshake\n";
$response = new Response("101");
$response = $response->withHeader('Upgrade', 'websocket')
->withHeader('Connection', 'Upgrade')
->withHeader(
"Sec-WebSocket-Accept",
base64_encode(
sha1(
$request->getHeaderLine('Sec-WebSocket-Key') . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
true
)
)
);
yield $response;
echo "Read loop\n";
$stream = $request->getBody();
while ($stream->isReadable()) {
// this does nothing
$x = (yield $stream->read(1));
echo $x, "\n";
}
}
}
$server = new Server(new WebSocketMiddleware());
$server->listen(8080);
Loop\run();
After sending response headers, I want to echo everything I receive from user, but nothing happens.
Can you point me in right direction?
Hello everyone, I get this error when I try to run the example server in the docs:
Fatal error: Declaration of class@anonymous::onError(int $code, Icicle\Socket\Socket $socket) must be compatible with Icicle\Http\Server\RequestHandler::onError($code, Icicle\Socket\Socket $socket) in /usr/local/src/icicle/bin/server on line 11
My composer.json:
{
"require": {
"icicleio/http": "^0.3.0"
}
}
Icicle\Http\Message\Response
requires ReadableStreamInterface
in its constructor:
public function __construct(
$code = 200,
array $headers = null,
ReadableStreamInterface $stream = null,
$reason = null,
$protocol = '1.1'
) {
parent::__construct($headers, $stream, $protocol);
$this->status = $this->validateStatusCode($code);
$this->reason = $this->filterReason($reason);
}
Is there a reason for that? I would say, it should be WritableStreamInterface
, but it wouldn't match with abstract Message
class.
Solution would be to move constructor away from Message
. What do you think?
I'm just wondering whether http(s) and socks proxy are in the roadmap too?
There is a bug when I would like to parse the following url:
/api/search/json?param_a=a¶m_b[]=b¶m_b[]=c
The $request->getRequestTarget() will be
/api/search/json?param_a=a¶m_b%5B%5D=c
and $request->getUri()->getQueryValues() will be
array(2) {
'param_a' =>
string(1) "a"
'param_b%5B%5D' =>
string(1) "c"
}
Maybe you can use the default parse_str() function
Hi,
I would like to ask if there are any plans for supporting HTTP2 for server side? Are there any technical challenges that makes this impossible?
Hello,
i create http server from example code and catch exception.
[Info @ 2016/08/12 18:38:32] HTTP server listening on ***
[Error @ 2016/08/12 18:38:51] Uncaught exception when creating response to a request from *** on * in file _/vendor/icicleio/http/src/Server/Server.php on line 334: A Icicle\Http\Message\Response object was not returned from :onRequest().
[Error @ 2016/08/12 18:38:51] Uncaught exception when creating response to a request from * on * in file _/vendor/icicleio/http/src/Server/Server.php on line 334: A Icicle\Http\Message\Response object was not returned from :onRequest().
[Notice @ 2016/08/12 18:41:05] Error when handling request from *: The stream is no longer readable.
PHP 7.0.8
The Message component interfaces looks an awful lot like PSR-7's interfaces. I'm sure that's not coincidental.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.