Reputation: 11
Folks,
I´m trying do code a simple socket sample in PHP. The following code seems to be working ok:
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
// Bind the source address
if( !socket_bind($sock, "127.0.0.1" , 5000) )
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not bind socket : [$errorcode] $errormsg \n");
}
echo "Socket bind OK \n";
if(!socket_listen ($sock , 10))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
echo "Socket listen OK \n";
echo "Waiting for incoming connections..... \n";
But when I add the line $client = socket_accept($sock); as just the next step, my aplication keeps in loading state for about 5 minutes and fails!
I researched stuff about but I can´t find a clue and much less a solution.
Thanks!
Upvotes: 1
Views: 806
Reputation: 1105
try running your script on CLI. should work like you want it to. Running it on the browser will eventually lead to a timeout.
Upvotes: 0
Reputation: 841
These are snippets from a working socket script of mine. It is skeletal, but you will catch the drift.
It's a blocking call unless you do something like this:
@socket_set_nonblock($sock);
And then loop continuously doing things with your connections and the data they send.
while(true){
if(($newc = @socket_accept($sock)) !== false) {
$con=1;
}
if($con==1){
//There is a socket. Read data from it, write data to it or close it here:
if($dataIn = socket_read($newc, 1024)){
echo "Client: " . $dataIn . "\r\n<BR>";
}
if($dataIn==""){
socket_close($newc);
return();
}
}
sleep(1);
}
Upvotes: 0
Reputation: 20899
From the documentation for socket_accept():
If there are no pending connections, socket_accept() will block until a connection becomes present.
Do you have anything attempting to connect to the application? If you don't, eventually socket_accept() will time out due to default_socket_timeout.
Upvotes: 1