zl程序教程

您现在的位置是:首页 >  其他

当前栏目

浅析PHPSocket技术

技术 浅析 phpsocket
2023-06-13 09:15:03 时间

phpsocketSocket位于TCP/IP协议的传输控制协议,提供客户-服务器模式的异步通信,即客户向服务器发出服务请求,服务器接收到请求后,提供相应的反馈或服务!我练习了一个最基本的例子:

使用并发起一个阻塞式(block)连接,即服务器如果不返回数据流,则一直保持连接状态,一旦有数据流传入,取得内容后就立即断开连接。代码如下:

复制代码代码如下:

<?php
$host=www.sohu.com;//这个地址随便,用新浪的也行,主要是测试用,哪个无所谓
$page="/index.html";
$port=80;
$request="GET$pageHTTP/1.1\r\n";
$request.="Host:$host\r\n";
//$request.="Referer:$host\r\n";
$request.="Connection:close\r\n\r\n";
//允许连接的超时时间为1.5秒
$connectionTimeout=1.5;
//允许远程服务器2秒钟内完成回应
$responseTimeout=2;
//建立一个socket连接
$fp=fsockopen($host,$port,$errno,$errstr,$connectionTimeout);
if(!$fp){
   thrownewException("Connectionto$hostfailed:$errstr");
}else{
   stream_set_blocking($fp,true);
   stream_set_timeout($fp,$responseTimeout);
}
//发送请求字符串
fwrite($fp,$request);
//取得返回的数据流内容
$content=stream_get_contents($fp);
echo$content;
$meta=stream_get_meta_data($fp);
if($meta["timed_out"]){
   thrownewException("Responsefromwebservicesservertimedout.");
}
//关闭Socket连接
fclose($fp);
?>