Ahoy Sailors!

So I've begone a Parent/Child based application, I've currently got both the scripts to connect to each other & send & receive text, However there are two bugs.

First when the Child connects too the Parent for the first time, It works! But if you exit & start the Child script again without closing the Parent, You get an "socket_recv(): unable to read from socket [11]: Resource temporarily unavailable" error.

Child.php

<?php
$addr="127.0.0.1";
$port=220;
$timeout=0;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
///////////////////
$dz = socket_connect($sock,$addr, $port);
$buf = "text";
$rec = socket_recv($sock, $buf, 2048,MSG_DONTWAIT);

while (1>0){

$buf = explode(":", $buf); //Function deciding
if ($buf[0]=='0'){
$fdb = "function not done yet";
}
if ($buf[0]=='1'){
echo $buf[1] . "\n";
}
sleep('5');
}
?>

__________________
The second is only minor, The parent script, Even though in a loop, Only sends the specified text once per connection? If you where to restart the Child script, Then it would send it once more.

Parent.php

<?php
$host = "127.0.0.1";
$port = 220;
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
// Networking area, Creating, Binding & finally listing
while (1>0){
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
$out = "1:Ahoy!";
socket_write($spawn, $out, strlen ($out)) or die("Could not write output\n");
echo "Sent!";
sleep(6);
}
?>

Recommended Answers

All 2 Replies

Props to you for having the most creative greeting I've seen on DaniWeb! :D
Ahoy Captain Syphilis (Sounds a little strange, but anyway),
I'd suggest registering socket_close() as a shutdown function after the child makes a connection. This way any early exits will close the socket before ending the script. I'm not sure if this will fix your problem, but give it a shot. It's my best guess at the current time.

//Create the close socket function
function closeSock() {
    //Grab the global sock variable & close it
    global $sock; //Make this $socket if in the parent
    socket_close($sock);
}

//Register yee function as when the user abandons ship
register_shutdown_funtion('closeSock');

Also, while were on that subject, why not close the register the socket_close() function as a shutdown function in the parent, just for good measure.
Good Luck Mate,
PhpMyCoder

yeah nice greeting mate! arr!:twisted:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.