I am trying to implement a simple socket server which accepts TCP connections and returns a response according to the input.
The entire program is running in a loop so that it is always on, but there is a significant delay before the socket_accept
function call.
When I execute the program, it takes about 10-15 seconds for the first echo "The server is ready" command to be executed.
I'm running this on a RedHat Enterprise Linux Server 5.5 (Tikanga) with PHP v. 5.1.6.
Any suggestions?
Code Snippet:
$host = "SERVER_IP";
$port = 80;
set_time_limit(100);
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo socket_strerror(socket_last_error($socket));
exit;
}
$result = socket_bind($socket, $host, $port) or die("Could not create socket\n");
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
while(true)
{
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
echo "\nThe server is ready\n";
$input = socket_read($spawn, 1024) or die("Could not read input\n");
$output = processInput($input);
socket_write($spawn, $output, strlen ($output)) or die("Could not wri开发者_JS百科te output\n");
socket_close($spawn);
}
socket_close($socket);
echo "\nTerminating\n";
socket_accept is a blocking method and it doesn't return unless it accepts a new socket connection. so your code will not print "The server is ready" unless your client calls a socket connect function and make a successful connection to your socket server. So the delay could be at your client end or maybe you are running your client after 10 to 15 seconds.
精彩评论