//以上php为服务端,它将监听消息,直到按下:ctrl+c
while(true)
{
//每5秒执行一次
receive_message('127.0.0.1','85',5);
}
//自定义函数用于获取消息
function receive_message($ips教程erver,$portnumber,$nbsecondsidle)
{
//创建socket
$socket=stream_socket_server('tcp://'.$ipserver.':'.$portnumber, $errno, $errstr);
if(!$socket)
{
//如果创建socket失败输出内容
echo "$errstr ($errno)
n";
}
else
{
//如果创建成功则接受socket连接并获取信息
while($conn=@stream_socket_accept($socket,$nbsecondsidle))
{
$message=read($conn,1024);
echo 'i have received that : '.$message;
fputs ($conn, "okn");
fclose ($conn);
}
fclose($socket);
}
}
//server结束
?>
<?php
//以下代码为客户端,它将发送信息并读取回复
send_message('127.0.0.1','85','message to send...');
//自定义函数,发送信息
function send_message($ipserver,$portserver,$message)
{
$fp=stream_socket_client("tcp://$ipserver:$portserver", $errno, $errstr);
if(!$fp)
{
echo "erreur : $errno - $errstr
n";
}
else
{
fwrite($fp,"$messagen");
$response = fread($fp, 4);
if($response != "okn")
{
echo 'the command couldn't be executed...ncause :'.$response;
}
else
{
echo 'execution successfull...';
}
fclose($fp);
}
}