当前位置: 移动技术网 > IT编程>开发语言>PHP > 浅析PHP Socket技术

浅析PHP Socket技术

2019年04月05日  | 移动技术网IT编程  | 我要评论

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

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

复制代码 代码如下:

<?php
$host = www.sohu.com; //这个地址随便,用新浪的也行,主要是测试用,哪个无所谓
$page = "/";
$port = 80;
$request = "get $page http/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) {
    throw new exception("connection to $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']) {
    throw new exception("responsefrom web services server timed out.");
}
//关闭socket连接
fclose($fp);
?>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网