douchengchen7959 2015-09-28 11:03
浏览 107

php socket_recvfrom多线程

I have a problem of waiting socket_recvfrom to receive something otherwise the script won't continue running

for( $i= 1024 ; $i <= 65535 ; $i++ ) {
$sock[$i] = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($sock[$i], $sourceips['madcoder'],$i);
socket_connect($sock[$i], '115.188.58.144 ', 1195);
$request = 'data';
socket_write($sock[$i], $request);
$from = '';
$port = 0;
$valeur = socket_recvfrom($sock[$i], $buf, 1222, 0, $from, $port);
}

this code basically send a udp request on a different local port each time and see if he got a response The pogramme now is stuck waiting to receive a packet thanks to socket_recvfrom

I want to make it run as fast as i could without risking to lose a response

i could use

socket_set_option($sock[$i], SOL_SOCKET, SO_RCVTIMEO, array('sec' => 1, 'usec' => 0));

but the problem is waiting for over a 1 second is too much and there is a problem with setting a value of under a second

changing the value to

array('sec' => 0, 'usec' => 100)

or

array('sec' => 0.1, 'usec' => 0)

won't work so i was thinking of multi threading ,The only way i know to multi thread is a "for" loop like i did but i really wish if i could try something else more effective

  • 写回答

1条回答 默认 最新

  • dtnqbre7980007 2015-09-28 11:55
    关注

    using pthreads, http://php.net/manual/en/book.pthreads.php , something like

    <?php
    class async_sender extends Thread {
    public function __construct($i,$sourceip){
      $this->i=$i;
      $this->sourceip=$sourceip;
    }
     public $sourceip;
     public $finished=false;
     public $response='';
     public $socket=NULL;
     public $i=-1;
    public function run(){
        $this->socket=socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
        socket_bind($this->socket, $this->sourceip,$this->i);
        socket_connect($this->socket, '115.188.58.144 ', 1195);
        $request = 'data';
        socket_write($this->socket, $request);
        $from = '';
        $port = 0;
    
        socket_recvfrom($this->socket, $this->response, 1222, 0, $from, $port);
        $this->finished=true;
    
    }
    }
    
    $sender_threads=array();
    for( $i= 1024 ; $i <= 65535 ; $i++ ) {
    $sender_threads[$i]=new async_sender($i,$sourceips['madcoder']);
    $sender_threads[$i]->start();
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog