Blake
Blake

Reputation: 140

PHP Socket Blocking

Basically, I'm using a blocking TCP socket along with socket_accept(). The problem I have, is that for obvious reasons since the I/O is blocking there can only be one connection to the socket at any one time that PHP is able to manipulate. I am fine with this, as this is the behaviour I am after.

However, if a client is to open a connection to the my PHP server, if they are simply leaving the socket open and sending no data, the socket and daemon are rendered useless as the blocking I/O will not allow new requests.

Is there a way to detect a client that is simply sending no data (like a no-transmission timeout) or something similar? I'd rather not use non-blocking I/O.

Upvotes: 0

Views: 1659

Answers (2)

david.wosnitza
david.wosnitza

Reputation: 763

I used Tudor Barbu Thread class to do some pseudo threading for a Websocket server once...

here's a gist: https://gist.github.com/eda7d47ec4e475af531e

Upvotes: 0

phihag
phihag

Reputation: 287835

You can simply call the equivalent of stream_set_timeout to make the blocking reads and writes terminate after a certain timeout:

$s = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!socket_bind($s, '127.0.0.1', 0)) die("bind failed");
if (!socket_listen($s)) die("listen failed");
socket_getsockname($s, $localA, $localPort);
echo 'Listening on ' . $localA . ': ' . $localPort . "\n";

$c = socket_accept($s);

// Warning: Ugly hack ahead.
// This just mitigates the problem somewhat, and doesn't actually solve it
socket_set_option($c, SOL_SOCKET, SO_RCVTIMEO, array('sec'=>2,'usec'=>0));
socket_set_option($c, SOL_SOCKET, SO_SNDTIMEO, array('sec'=>2,'usec'=>0));

$r = socket_read($c, 1024);
echo 'read finished: got ' . var_export($r, true) . "\n";

Note that this is a hack; a malicious attacker can still send only 1 byte per second or so.

Instead of investing time in these crazy hacks, you should really switch to non-blocking IO or handle the accepted sockets in a separate thread/process.

Upvotes: 1

Related Questions