这段代码可能非常有用...
以下代码用于“服务器”。它监听消息,直到按下 CTRL-C
<?php
while (true)
{
receive_message('127.0.0.1','85',5);
}
function receive_message($ipServer,$portNumber,$nbSecondsIdle)
{
$socket = stream_socket_server('tcp://'.$ipServer.':'.$portNumber, $errno, $errstr);
if (!$socket)
{
echo "$errstr ($errno)<br />\n";
}
else
{
while ($conn = @stream_socket_accept($socket,$nbSecondsIdle))
{
$message= fread($conn, 1024);
echo '我已收到:'.$message;
fputs ($conn, "OK\n");
fclose ($conn);
}
fclose($socket);
}
}
?>
以下代码用于“客户端”。它发送消息并读取响应...
<?php
send_message('127.0.0.1','85','发送的消息...');
function send_message($ipServer,$portServer,$message)
{
$fp = stream_socket_client("tcp://$ipServer:$portServer", $errno, $errstr);
if (!$fp)
{
echo "错误:$errno - $errstr<br />\n";
}
else
{
fwrite($fp,"$message\n");
$response = fread($fp, 4);
if ($response != "OK\n")
{echo '命令无法执行...\n原因:'.$response;}
else
{echo '执行成功...';}
fclose($fp);
}
}
?>