Hello my PHP gurus.
I have something for you to sink your teeth into.
let me show you my code im working with:
PHP Code:
<?PHP
/* Simple Socket Server v1.0 */
// set some variables
$host = gethostbyname(gethostname());
$port = 9996;
// don't timeout!
set_time_limit(0);
// 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");
socket_set_block($socket);
echo("Waiting for socket connection on " . $host . ":" . $port . "\n\r");
// accept incoming connections
// spawn another socket to handle communication
$socketAccept = '';
$socketAccept = socket_accept($socket) or die("Could not accept incoming connection\n");
echo("Incomming connection accepted!\n\r");
// Make a file to save incoming socket data to
$randFileName = 'test_' . md5(mt_rand(0, 1000) ) . '.test';
$inFileHandle = fopen($randFileName, 'wb');
while(!$input == '')
{
// read client input
$input = socket_read($socketAccept, 1024) or die("Could not read input\n\r");
// save data to file
fwrite($inFileHandle, $input, 1024);
}
// close file handle
fclose($inFileHandle);
echo("Socket file data read and saved to\n\r" . $randFileName . "\n\r");
// shut down sockets
/*
socket_shutdown($socketAccept, 2);
socket_shutdown($socket, 2);
*/
// close sockets
socket_close($socketAccept);
socket_close($socket);
echo("Sockets closed!\n\r\n\r");
?>
This script works the first time itīs run and my client script on another computer sends data and this server script saves it to a file. And all is well.
Now.. the problem is that when i want to run the server script again and try to send data to it with my client script. The client script gives the error that a connection on the server script is blocking the socket_write() function in my client script.
It would seem that the socket first opened the first run on the server script is still open and wont accept new connections.
I canīt get whats wrong. Im really looking for your advice.
By request i can post the client script also, but i donīt think its where the problem lies.
Sorry for the english :)
Note:
- I am running the script from Win7 command line via the php.exe executible.
Thank you in advance.