Rumah >pembangunan bahagian belakang >tutorial php >socket - php pthreads主线程如何获取到子线程的scoket资源?
php pthreads主线程如何获取到子线程的scoket资源?
最近公司要做的一个业务是,要用amqp的consume方法监听队列,同时与多个终端保持连接,一旦队列里有消息就马上下发给终端,不能有延迟,
我想到的是只能用线程来做,如果用多进程来实现,socket资源是不能共享的,但是现在用了pthreads 扩展也不行,从主线程中无法获取到子线程中的连接,大侠们请教下怎么弄
<code> <?php class PrintServer extends Thread{ public $connections = array(); public function __construct() { $this->connections = array(); } public function run(){ $connections = array(); //监听端口 $PORT = 8888; $sock = socket_create_listen($PORT); if (!$sock) { exit(1); } //不阻塞 socket_set_nonblock($sock); while (true) { // $readfds = array_merge($this->connections, array($sock)); $readfds = array_merge($connections, array($sock)); $writefds = array(); //选择一个连接,获取读、写连接通道 $e= null; $flag = socket_select($readfds, $writefds, $e, $t = 5); if ($flag) { foreach ($readfds as $rfd) { if ($rfd == $sock) { //接受客户端连接 $newconn = socket_accept($sock); $i = (int)$newconn; //将当前客户端连接放如socket_select选择 $connections[$i] = $newconn; //输入的连接资源缓存容器 $writefds[$i] = $newconn; var_dump($connections); $this->connections = $connections; var_dump($this->connections); echo "Welcome to the PHP Chat Server!\n"; continue; } } } echo "a\n"; } } } $my = new PrintServer(); $my->start(); while(true){ var_dump($my->connections); sleep(3); } </code>
php pthreads主线程如何获取到子线程的scoket资源?
最近公司要做的一个业务是,要用amqp的consume方法监听队列,同时与多个终端保持连接,一旦队列里有消息就马上下发给终端,不能有延迟,
我想到的是只能用线程来做,如果用多进程来实现,socket资源是不能共享的,但是现在用了pthreads 扩展也不行,从主线程中无法获取到子线程中的连接,大侠们请教下怎么弄
<code> <?php class PrintServer extends Thread{ public $connections = array(); public function __construct() { $this->connections = array(); } public function run(){ $connections = array(); //监听端口 $PORT = 8888; $sock = socket_create_listen($PORT); if (!$sock) { exit(1); } //不阻塞 socket_set_nonblock($sock); while (true) { // $readfds = array_merge($this->connections, array($sock)); $readfds = array_merge($connections, array($sock)); $writefds = array(); //选择一个连接,获取读、写连接通道 $e= null; $flag = socket_select($readfds, $writefds, $e, $t = 5); if ($flag) { foreach ($readfds as $rfd) { if ($rfd == $sock) { //接受客户端连接 $newconn = socket_accept($sock); $i = (int)$newconn; //将当前客户端连接放如socket_select选择 $connections[$i] = $newconn; //输入的连接资源缓存容器 $writefds[$i] = $newconn; var_dump($connections); $this->connections = $connections; var_dump($this->connections); echo "Welcome to the PHP Chat Server!\n"; continue; } } } echo "a\n"; } } } $my = new PrintServer(); $my->start(); while(true){ var_dump($my->connections); sleep(3); } </code>