2011-09-12 47 views
2

你好我做了一個php套接字服務器來從plc獲取數據,plc被配置爲tcp套接字客戶端。 我有一個連續的問題,如果本地網絡下去似乎功能socket_accept停滯,plc無法發送給我的數據。 如果我重新啓動我的服務器PLC重新正確連接。php socket_accept停止

有人可以幫我嗎? 我的服務器代碼:

error_reporting(E_ALL); 

/* Allow the script to hang around waiting for connections. */ 
set_time_limit(0); 

/* Turn on implicit output flushing so we see what we're getting 
* as it comes in. */ 
ob_implicit_flush(); 

$address = ipserver; 
$port = 10001;  

if (($sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname("TCP"))) === false) { 
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n"; 
    exit; 
} 

if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) { 
    echo socket_strerror(socket_last_error($sock)); 
    exit; 
} 

if (socket_bind($sock, $address, $port) === false) { 
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"; 
    exit; 
} 

if (socket_listen($sock, 5) === false) { 
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"; 
    exit; 
} 

    while(true) 
{ 
    //$remote_fd = socket_accept($sock); 
    if (($remote_fd = socket_accept($sock)) === false) { 
     echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"; 
     break ; 
    } 
    do { 
     $recv = ""; 
     if (false === ($recv = socket_read($remote_fd, 128, PHP_BINARY_READ))) { 
      echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($remote_fd)) . "\n"; 
      #break 2; 
     } 
     if($recv != "") { 
      echo $recv."\n"; 
      inserisci_letture("t_letture",trim($recv)); 
      if($sent=socket_write($remote_fd,"1",1)===false) 
      { 
       echo "socket_write() failed: reason: " . socket_strerror(socket_last_error($remote_fd)) . "\n"; 
      } 
     } 
    } 
    while($recv != ""); 
} 
socket_shutdown($sock); 
socket_close($sock); 


?> 
+0

嘗試綁定到地址0.0.0.0在socket_bind() – arnaud576875

+0

PLC連接到服務器與特定的端口和IP我不能改變它。 – user940945

+0

0.0.0.0用於監聽每個接口,而不是一個特定的接口;這可能會解決您的問題,因爲如果網絡遭到關閉,它將不會關閉套接字。 – arnaud576875

回答

0

偵聽0.0.0.0,而不是特定的接口,從而使套接字沒有關閉,如果網絡(接口)做了下來。這是一個監聽所有接口的特殊地址。

+0

謝謝,但只能改變綁定函數?剩下的代碼保持不變?另一個非常奇怪的事情是,在Windows上的一個簡單的delphi套接字客戶端,這不是uppens。但我想使用Linux系統,給我更多的穩定性和可能性 – user940945

+0

最後詳細我的Linux服務器我主機的VMWare虛擬機。我嘗試綁定在0.0.0.0謝謝很多 – user940945

+0

正確的解決方案是分叉我的服務器我使用梨網:服務器和plc可以連接和發送緩衝區中的數據 – user940945