I created a PHP's socket server. I connected to it using telnet or putty and everything works just well, until I tried to connect to in a .Net application, each time I execute the app it closes the server, here's my C# code, just the two lines:
System.Net.Sockets.TcpClient cli = new System.Net.Sockets.TcpClient("192.168.0.200", 10000);
cli.Close();
When I run the app the PHP socket server is closed with this error:
Warning: socket_read(): unable to read from socket [0]: An existing connection was forcibly closed by the remote host
I tried commenting out the Cli.close()
line, and sure enough the socket stayed open until the C# app is closed, then it will close with the same error message above.
So what is causing the problem?, client should not be able to close the socket this way.
Thank you
Looking at the code at http://php.net/manual/en/sockets.examples.php I do not see any problems with it. This code exists the script when socket is closed:
if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
What I can suggest is to modify the code as follow:
if (false === ($buf = @socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break;
}
Adding '@' will prevent warning to appear. Changing break 2;
to break;
will make server not to exit but to keep waiting for a next connection.
If this doesn't work than you can wrap the whole script to another do { } while()
loop so that every time the socket read fails php do socket_create()
again.