PHP Socket 编程示例

<?php
 
//php socket 客户端编程
// 建立一个socket并连接
 
//选项 SO_REUSEADDR¦SO_REUSEPORT¦TCP_NODELAY¦SO_RCVTIMEO¦SO_SNDTIMEO
//SO_REUSEPORT 端口重用 linux kernel >3.9
//SO_RCVTIMEO 接收数据超时
//SO_SNDTIMEO发送数据超时
//设置socket选项
 
//$host = "34.56.33.33";
$host = "192.168.6.156";
$port = "1883";
$timeout = 2; //连接超时/秒
 
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
 
//连接 超时处理
socket_set_nonblock($socket);
$time = time();
while (!@$connection=socket_connect($socket, $host, $port))
{
$err = socket_last_error($socket);
if ($err == 115 ¦¦ $err == 114)
{
if ((time() - $time) >= $timeout)
{
socket_close($socket);
die("连接超时. \n");
}
usleep(1);
continue;
}
die(socket_strerror($err) . "\n");
}
socket_set_block($socket);
/*if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEPORT, 1)) {
echo '不能在socket上设置选项: '. socket_strerror(socket_last_error()) . PHP_EOL;
}*/
 
if (!socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 1, 'usec' => 100))) {//接收数据超时
echo '不能在socket上设置选项: '. socket_strerror(socket_last_error()) . PHP_EOL;
}
 
/*
while($buffer = socket_read($socket, 1024, PHP_NORMAL_READ))
{
if($buffer == "无数据")
{
echo("<p>无数据</p>");
break;
}
else
{
echo("<p>缓冲数据: " . $buffer . "</p>");
}
}*/
echo("<p>写入Socket</p>");
//写入测试数据到 socket
if(!socket_write($socket, "SOME DATA \r\n"))
{
echo("<p>写入失败</p>");
}
//读取 socket的响应
while($buffer = socket_read($socket, 1024/*, PHP_NORMAL_READ*/))
{
echo("<p>发送数据为: SOME DATA<br> 响应:" . $buffer . "</p>");
}
echo("<p>从socket读取完成</p>");
?>
 
 
 
转载请注明 来自Lenix的博客 ,地址http://blog.p2hp.com/archives/4380

 

PHP Socket 编程示例
标签: