PHP 通过tcp协议连接远程服务器简单例子
PHP可以通过socket 的一些方法连接TCP server,就我知道的有两种方法:
1. 用fstockopen() 函数连接
直接上例子:
$host="10.50.75.20";
$port = 4700;
$timeout = 30;
// open a client connection
try{
$fp = fsockopen ($host, $port, $errno, $errstr,$timeout);
}
catch (Exception $e) {
echo "Caught exception: ",$e->getMessage(),"\n";
exit;
}
if (!$fp)
{
$result = "Error: could not open socket connection";
}
else
{
fwrite ($fp, $message);
// get the result
//while (!feof($fp)) {
//$result .= fgets($fp, 128);
//}
//$result .= fgets ($fp, 1024);
// close the connection
fputs ($fp, "END");
fclose ($fp);
// trim the result and remove the starting ?
$result = trim($result);
$result = substr($result, 2);
}
2. 用socket_Connect() 函数连接
例子:
$sendStr=“client send messages”;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)
or die("Unable to create socket\n");
//socket_set_nonblock($socket)
//or die("Unable to set nonblock on socket\n");
$time = time();
while (!@socket_connect($socket, $host, $port))
{
$err = socket_last_error($socket);
if ($err == 115 || $err == 114)
{
if ((time() - $time) >= $timeout)
{
socket_close($socket);
die("Connection timed out.\n");
}
sleep(1);
continue;
}
die(socket_strerror($err) . "\n");
}
socket_send($socket,$sendStr,strlen($sendStr),0);
socket_close($socket);