I'm writing a script which will accept multiple socket connections in background and do some job received by gearman (in this case forget about gearman)
class ListenerThread extends Thread
{
public function run(){
$host = '192.168.30.119';
$port = 5010;
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($socket, $host, $port);
socket_listen($socket);
$client = array($socket);
global $clientsArr;
do{
socket_select($client, $write = NULL, $except = NULL, $tv_sec = NULL);
if(in_array($socket, $client)){
$tmp = socket_accept($socket);
socket_write($tmp, "who are you\n");
$request = trim(socket_read($tmp, 2024));
echo "new client connected\n";
$clientsArr[] = $tmp;
$client[] = $tmp;
}
} while(true);
}
}
global $clientsArr;
$clientsArr = new Threaded();
$listener = new ListenerThread();
$listener->start(PTHREADS_INHERIT_ALL | PTHREADS_ALLOW_GLOBALS);
for($i = 0; $i < 100; $i++){
print_r($clientsArr);
sleep(2);
}
and now when I run this code and connect client with telnet 192.168.30.119 5010 I am getting strange output
OUTPUT
new client connected
Threaded Object
(
[0] => Resource id #4
)
Threaded Object
(
[0] => Resource id #5
)
Threaded Object
(
[0] => Resource id #6
)
Why is thread or something else changing resource even there is no more than one connection?
Please note that this is first time I'm using threads so if someone has a better solution please share.
The goal is to have a background loop which will listen on port and store connections in array or object which should be accessible outside of class.