Page 1 of 1

Socket problems

Posted: Thu May 18, 2006 6:28 pm
by vasilanthropos
Hello, i try to connect to a server(writen in c) that i am running locally in my pc but after
connecting, writing some data and getting a reply the connection closes. The server doesn't
have a problem as in telnet there is no problem.

Re: Socket problems

Posted: Thu May 18, 2006 7:01 pm
by alex.barylski
vasilanthropos wrote:Hello, i try to connect to a server(writen in c) that i am running locally in my pc but after
connecting, writing some data and getting a reply the connection closes. The server doesn't
have a problem as in telnet there is no problem.
PHP is NOT typically run in a tsr mode...so thats likely where your problems are coming in...

PHP executes...opens connections...does it's business and regardless of whether you explicitly close a socket connection or any resource connection...that connection is closed and cleaned up by garbage collection facilities...

Some connections can be made persistent, like mysql_pconnect() for instance...but I'm not so sure how that works in PHP as PHP applications don't have an message pump or any way of interacting/manipulating the direction of code execution...except through GET/POST/ENVARS/etc...sooo...unless that connection is somehow persisted through requests (sessions don't allow resources to be persisted) I'm not sure what you can do about it...

After re-reading your message I'm not sure I understand what your asking...

Why don't you just close the connection directly in PHP??? Before script termination?

Posted: Thu May 18, 2006 7:27 pm
by s.dot
You'll likely want to have your own script dedicated to listening to the connection. An infinite loop is a possibility...

Code: Select all

while(TRUE){
  //listen for data, slice it, dice it, serve it somewhere
}
Obviously if the server crashes for some reason, this loop won't work. So perhaps a cronjob to check the connection as well wouldn't be a bad idea.

Posted: Fri May 19, 2006 2:24 am
by vasilanthropos
The problem is that the connection closes after the first send/read of data. I don't want it to close as
i want to send more data later.

Posted: Fri May 19, 2006 2:36 am
by Christopher
Can you show us the PHP code that you are using to make the connection?

Posted: Fri May 19, 2006 3:11 am
by vasilanthropos
function connect(){
global $socket;
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
$connection=socket_connect($socket,'localhost',1972);
}

This is how i do the connection. I also wrote how i read.

$display=socket_read($socket,1024,PHP_NORMAL_READ);

Posted: Fri May 19, 2006 6:27 am
by s.dot
If you're running this through a script, your connection to the socket will terminate at the end of the script.

You should put it inside of a loop to keep the connection open.

Code: Select all

while($display=socket_read.....){
    //
}

//or

while(TRUE){
  if($display=socket_read()){
    echo $display;
  }
}