2017-01-27 144 views
0

我想通過php腳本與我的TCP服務器通信,但我只能發送命令一次,如果我再發送然後在腳本中顯示數據發送但服務器中我不不迴應任何命令。基本上發送命令後,我想發送退出命令並關閉套接字。TCP服務器不接受第二個套接字發送

<?php 

echo "<br>Message send successfully \n"; 
if (isset($_POST['action'])) { 
switch ($_POST['action']) { 
    case 'open': 
     $message = "CO1OX\n"; 
     break; 
    case 'close': 
     $message = "CO1CX\n"; 
     break; 
} 
} else { 
$error = "Post error"; 
} 


if (!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) { 
    $errorcode = socket_last_error(); 
    $errormsg = socket_strerror($errorcode); 
    die("Couldn't create socket: [$errorcode] $errormsg \n"); 
} 

echo "Socket created <br/>"; 
//Connect socket to remote server 
if (!socket_connect($sock, '127.0.0.1', 13000)) { 
    $errorcode = socket_last_error(); 
    $errormsg = socket_strerror($errorcode); 
    die("Could not connect: [$errorcode] $errormsg \n"); 
} 
echo "Connection established <br/>"; 

if (!($sent_data = socket_send($sock, $message, strlen($message), 0)))    
{ 
    $errorcode = socket_last_error(); 
    $errormsg = socket_strerror($errorcode); 
    die("Could not send data: [$errorcode] $errormsg \n"); 
} 

$message="exit\n"; 
if(!($sent_data = socket_send($sock, $message, strlen($message), 0))) 
     { 
     $errorcode = socket_last_error(); 
     $errormsg = socket_strerror($errorcode); 
     die("Could not send data: [$errorcode] $errormsg \n"); 
} 
socket_shutdown($sock, 2); 
socket_close($sock); 
?> 

我試過與telnet通信,它工作正常。任何幫助都會很棒。

回答

0

我通過在兩個連續消息之間放置1ms的睡眠來解決這個問題。

相關問題