1

I have TCP Socket server using react\socket.

Depending on received data from the client, it doing something, then it close connection with the client.

The problem is i can't understand how to make connection timeout, if the server have not received any data for a period of time, how to close connection?

I'm looking for same as i did with stream_socket_accept() using stream_set_timeout()

<?php

require __DIR__ . '/vendor/autoload.php';

$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);

$socket->listen(2222);

$socket->on('connection', function ($conn) {

    $conn->on('data', function ($data) use ($conn) {

        if (substr($data, 0, 3) == 'one') {
            $conn->end('end_two');
        }
        else if (substr($data, 0, 3) == 'two') {
            $conn->end('end_two');
        }
        else {
            $conn->close();
        }
    });

});
$loop->run();
stream_set_timeout($client, 5);
4

1 回答 1

4

You need to add a timer to your $loop like in the example below.

$loop = React\EventLoop\Factory::create();

$socket = new React\Socket\Server($loop);
$socket->on('connection', function ($conn) use ($loop) {
    $func = function () use ($conn) {$conn->close();};
    $timer = $loop->addTimer(1, $func);
    $conn->on('data', function ($data) use ($loop, &$timer, $func) {
       $timer->cancel();
       $timer = $loop->addTimer(1, $func);
    });
});

Example from:

https://github.com/reactphp/socket/issues/42

于 2016-11-29T14:47:24.113 回答