簡體   English   中英

這是使用PHP連接到TCP端口的正確方法嗎?

[英]Is this the correct way to connect to a TCP port using PHP?

服務正在偵聽1xx.xxx.xx.xx上的端口1234我正在使用php fsockopen()與服務建立tcp連接! 我必須將傳入數據發送到服務,並將從服務中獲得的回復保存在文件中。 第一次發送數據時,建立了連接。 該代碼第二次再次嘗試打開端口,而這一次該服務提示SP嘗試連接。 拒絕連接。 存在活動的SP連接。 SP已關閉。

我該如何克服這個問題?

#!/usr/local/php5/bin/php-cgi
<?php 
//The Client
error_reporting(E_ALL);
$CONTENT = $_GET["DATA"]."";
echo urldecode($CONTENT);
$Handle = fopen("/xxx/xxx/xxx.txt", "a");
fwrite($Handle, $CONTENT);
fclose($Handle);

//$address = "1xx.xxx.xx.xx";
//$port = 1234;

/* Create a TCP/IP socket. */
$fp = fsockopen("tcp://1xx.xxx.xx.xx",1234 , $errno, $errdesc); 
if ( ! $fp ) {
  die ( "Couldn't connect to 1xx.xxx.xx.xx :\nError: $errno\nDesc: $errdesc\n" );
}
fputs ( $fp, $CONTENT );
while ( ! feof( $fp ) ) {
  $output = fgets( $fp, 2048 );
}
fclose( $fp );
$Handle1 = fopen("/xxx/xxx/yyy.txt", "a");
fwrite($Handle1, $output);
fclose($Handle1);

?>

另外請注意:您需要更換

while ( ! feof( $fp ) ) {
  $output = fgets( $fp, 2048 );
}

$output=''
while ( ! feof( $fp ) ) {
  $output .= fgets( $fp, 2048 );
}

因為$output = fgets( $fp, 2048 ); 在每個迭代循環中覆蓋$ output內容。

關於您的問題-我認為服務中存在一些錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM