|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2004-04-25 06:56 UTC] php at richardneill dot org
Description:
------------
According to the documentation, socket_read() can return:
1)A string - normal data
2)An empty string "" - the other end closed the connection
3)false - something went wrong.
But it seems to be returning false on connection close.
Reproduce code:
---------------
$buffer=socket_read($socket,2048,PHP_NORMAL_READ);
if ($buffer===false){
echo "Error: socket_read() failed: reason: ".socket_strerror(socket_last_error())." \n";
exit (1);
}elseif ($buffer==''){
echo "Socket $socket returned an empty string. Closing connection\n";
socket_close($socket);
}else{
echo "Received data".trim($buffer)."\n";
}
Expected result:
----------------
I'm using netcat as a client, and then killing the netcat process with Ctrl-C to simulate remote host disconnecting.
I expect to see the socket close.
Actual result:
--------------
Actually, the php script exits, because socket_read returns
false instead of "".
This may be a bug in the documentation for socket_read, rather than in its behaviour.
Thanks for your help - Richard
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 22 07:00:01 2025 UTC |
There is no bug to fix here. You're actually getting "Connection reset by peer" (ECONNRESET) and that makes recv() to return -1 -> PHP socket_read() returns an error and FALSE. Here's simplified WORKING script: #!/usr/local/bin/php <?php error_reporting(E_ALL); /* Allow the script to hang around waiting for connections. */ set_time_limit(0); /* Turn on implicit output flushing so we see what we're getting as it comes in. */ ob_implicit_flush(); $address = '127.0.0.1'; $port = 1111; $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_bind($sock, $address, $port); socket_listen($sock, 5); do { $msgsock = socket_accept($sock); do { $buf = socket_read($msgsock, 2048, PHP_NORMAL_READ); var_dump($buf); } while ($buf !== FALSE && $buf !== ''); echo socket_strerror(socket_last_error($msgsock)); socket_close($msgsock); echo "Closed msgsocket; waiting for another connection\n"; } while (true); socket_close($sock); echo "Closed main socket, exiting\n"; ?>