php socket 超时时间,php socket如何设置超时时间

本文详细介绍了如何在PHP中使用Socket设置发送和接收超时时间,提供了一个示例函数`sendUdp`,该函数用于发送UDP数据包并可等待指定时间接收响应。通过设置SO_RCVTIMEO和SO_SNDTIMEO选项来控制超时,同时处理接收到的数据。函数还包含了处理分块接收和确认回复的逻辑。
摘要由CSDN通过智能技术生成

php socket设置超时时间的方法:【socket_set_option($socket,SOL_SOCKET,SO_SNDTIMEO,array("sec"=>6, "usec"=>0))】。

cbe3a9d876ecae44e83fd5b0bb798a36.png

【相关学习推荐:php编程(视频)】

php socket设置超时的方法:

php创建socket的方法和设置超时的方法,贴出来分享一下//如果$waitAckSec=0,则返回成功发送的字节

//如果$waitAckSec大于0,则返回发送后接收到得内容

//任何情况下,失败都返回FALSE

function sendUdp($host, $port, $buff,$waitAckSec=0) {

$socket = ($result = @socket_create(AF_INET,SOCK_DGRAM,SOL_UDP));

//发送超时1秒

socket_set_option($socket,SOL_SOCKET,SO_RCVTIMEO,array("sec"=>3, "usec"=>0 ) );

//接收超时6秒

socket_set_option($socket,SOL_SOCKET,SO_SNDTIMEO,array("sec"=>6, "usec"=>0 ) );

if($socket){

$result = @socket_sendto($socket,$buff,strlen($buff),0,$host,$port);

if($waitAckSec>0){

$result = FALSE;

$read = array($socket);

$write = NULL;

$except = NULL;

if(@socket_select($read,$write,$except,$waitAckSec)>0){

$fromHost = "";

$fromPort = 0;

@socket_recvfrom($socket,$result,4096,0,$fromHost,$fromPort);

$result = phpext_unpack($result);

if($result["needAck"] == 1){

$this->sendUdp($host, $port, $result["ackdata"]);

if(isset ($result['data']['list']) && isset ($result['data']['totalCount'])){

$list = $result['data']['list'];

$count = $result['data']['totalCount'];

while($count> count($list)){

@socket_recvfrom($socket,$result_temp,4096,0,$fromHost,$fromPort);

$result_temp = phpext_unpack($result_temp);

$this->sendUdp($host, $port, $result_temp["ackdata"]);

$list = array_merge($list,$result_temp['data']['list']);

}

$result['data']['list'] = $list;

}

}else{

@socket_recvfrom($socket,$result,4096,0,$fromHost,$fromPort);

$result = phpext_unpack($result);

if($result["needAck"] == 1){

$this->sendUdp($host, $port, $result["ackdata"]);

if(isset ($result['data']['result']) && isset ($result['data']['userID'])){

$list = $result['data']['list'];

$count = $result['data']['totalCount'];

while($count> count($list)){

@socket_recvfrom($socket,$result_temp,4096,0,$fromHost,$fromPort);

$result_temp = phpext_unpack($result_temp);

$this->sendUdp($host, $port, $result_temp["ackdata"]);

$list = array_merge($list,$result_temp['data']['list']);

}

$result['data']['list'] = $list;

}

}

}

}else{

$result = SEND_UDP_ERROR;

}

}

@socket_close($socket);

}

return $result;

}想了解更多编程学习,敬请关注php培训栏目!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值