PHP 通过tcp协议连接远程服务器简单例子
PHP可以通过socket 的一些方法连接TCP server,就我知道的有两种方法:
1. 用fstockopen() 函数连接
直接上例子:
<?PHP
/**
* PHP 通过tcp协议连接服务器方法
* @param
* @arrange (512.笔记) jb51.cc
**/
$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);
}
/*** 来自编程之家 jb51.cc(jb51.cc) ***/
2. 用socket_Connect() 函数连接
例子:
<?PHP
/**
* PHP 通过tcp协议连接服务器方法
* @param
* @arrange (512.笔记) jb51.cc
**/
$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);
/*** 来自编程之家 jb51.cc(jb51.cc) ***/
原文链接:https://www.f2er.com/php/527940.html