eio_read - not read sockets, only local files

Create issue
Issue #5 invalid
Alex Sky created an issue

This not work, result int(-1)

<?php

$fd = stream_socket_client('tcp://google.com:80');
fwrite($fd, "GET / HTTP/1.0\r\n\r\n");

eio_read($fd, 64, 0, EIO_PRI_DEFAULT, function($fd, $res){var_dump($res);}, $fd); // int(-1)
eio_event_loop();

This work

<?php
$fd = fopen(__FILE__, 'r');
eio_read($fd, 64, 0, EIO_PRI_DEFAULT, function($fd, $res){var_dump($res);}, $fd);
eio_event_loop();

Comments (5)

  1. Ruslan Osmanov repo owner

    You might check the actual error with eio_get_last_error(). The error is Illegal seek.

    If the offset is positive or zero, libeio calls pread() with the specified offset. Otherwise, read() is called. The file descriptor generated by stream_socket_client() is not capable of seeking, apparently(and it shouldn't be). So we have to specify a negative offset:

    <?php
    $fd = stream_socket_client('tcp://google.com:80');
    
    fwrite($fd, "GET / HTTP/1.0\r\n\r\n");
    
    eio_read($fd, 64, -1, EIO_PRI_DEFAULT,
        function($data, $res, $req) use ($n_chars)
        {
            if ($res != 0) {
                fprintf(STDERR, "Error: %s\n", eio_get_last_error($req));
                return;
            }
    
            printf("%s\n%s\n%s\n",
                str_repeat('>', 12),
                $res,
                str_repeat('<', 12));
        }, $fd); // int(-1)
    eio_event_loop();
    

    Now the script fetches desired 64 characters of HTTP response:

    php script.php
    >>>>>>>>>>>>
    HTTP/1.0 302 Found
    Cache-Control: private
    Content-Type: text/h
    <<<<<<<<<<<<
    
  2. Alex Sky reporter

    Thanks, didn't know!

    Say, you want to make PHP wrapper for libuv? https://github.com/libuv/libuv

    (libuv == libev+libeio + huge community) libuv, better because it has everything you need and a huge community. It is very lacking in PHP

    Thank.

  3. Ruslan Osmanov repo owner

    @ua-san I wrote the async PHP extensions for fun. Now I guess it's enough for me. At least, I've no motivation to writing an ext. for libuv.

  4. Log in to comment