Jump to content

Need Help With Sockets in PHP


gaza165

Recommended Posts

I am trying to formulate a script that can output strings using sockets.

 

so far i have this code that creates and provides the user with a welcome message.

 

<?php

// don't timeout
set_time_limit (0);

// set some variables
$host = "192.168.81.130";
$port = 3333;

// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create
socket\n");

// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to
socket\n");

// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket
listener\n");

echo "Waiting for connections...\n";

// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming
connection\n");

echo "Received connection request\n";

// write a welcome message to the client
$welcome = "Roll up, roll up, to the greatest show on earth!\n? ";
socket_write($spawn, $welcome, strlen ($welcome)) or die("Could not send
connect string\n");

?>

 

i then open another file that gets the welcome message and displays it to the user.

 

<?php

$host="192.168.81.130";
$port = 3333;



// open a client connection
$fp = pfsockopen ($host, $port, $errno, $errstr);

if (!$fp)
{
      $result = "Error: could not open socket connection";
}
else
{
  // get the welcome message
     	$result .= fgets ($fp, 1024);
}


?>
Server said: <b><? echo $result; ?></b>

 

This works fine, however, once the script has finished the connection the to the socket server is close, how do i keep the session persistently open to keep feeding and outputting new strings??

 

Thanks

 

Garry

Link to comment
Share on other sites

You want to look into AJAX, using AJAX you can make server calls and it can re-run the connection and check for new messages. Other than that you have to do a forced reload, as even just sleep the script while setting the set_time_limit to infinite will slow down your server a ton by eating up the memory. Better to do the AJAX calls and get the data that way.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.