Continuously running socket connection

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
silky
Forum Newbie
Posts: 1
Joined: Thu Feb 05, 2004 10:28 am

Continuously running socket connection

Post by silky »

I have a server that is going to have a continuous socket connection on linux. Is there a way with php to send information to that socket? I currently have code to open a socket send information, receive a response, and then close the socket. However this socket is going to be open already and I need to be able to send data to it and retrieve data from it.

Here is what I currently have.

$host = "100.100.100.100";
$port = 21572;

//Open a client connection
$fp = fsockopen($host, $port, $errno, $errstr);

if (!$fp){
$result = "Error: Could not open socket connection";
}else{
//Write the user string to the socket
fputs ($fp, $output, strlen($output));

socket_set_timeout($fp, 30);

//Get Respones
//Get first five bytes to determine full size
$result = fread($fp, 5);
$bytes_left = socket_get_status($fp);

//Get the remaining results with known byte size
$result .= fread($fp, $bytes_left["unread_bytes"]);

//close the connection
fclose($fp);
}

This currenly works, but the server I am contacting would like me to have the socket open at all times. Therefore I need to send data to the already open socket. :?

Thanks in advance,
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

Post by kettle_drum »

Just use something like:

Code: Select all

while($stay_connected){
   #run any socket stuff you need in here - and it will repeat until you set $stay_connected to 0.
}
and run some checks in the while loop to make sure the socket is still open and maybe every few thousand loops send char of data to make sure the other server is still alive.
Post Reply