2015-04-06 219 views
1

我想在Java中的SocketServer(服務器)和php中的Socket(客戶端)之間建立通信。 客戶端能夠連接到主機,客戶端能夠發送消息並且服務器成功讀取消息。但問題出現時,套接字服務器寫入客戶端,客戶端不接收來自服務器的消息。SocketServer在java服務器和php客戶端之間的通信

我已經讀過關於同一場景(java-php套接字通信)的其他問題,但我似乎無法找到導致問題的原因。

如果我使用Java Socket作爲客戶端,那麼通信在兩種方式中都可以完美地工作。

服務器:

import java.io.*; 
import java.net.ServerSocket; 
import java.net.Socket; 

public class Server { 

    protected ServerSocket socket; 
    protected final int port = 9005; 
    protected Socket connection; 
    protected String command = new String(); 
    protected String responseString = new String(); 

    public void init(){ 

     System.out.println("Launching Server: "); 
     try{ 
      socket = new ServerSocket(port); 


      while(true) 
      { 
       // open socket 
       connection = socket.accept(); 
       System.out.println("Client Connected "); 

       // get input reader 
       InputStreamReader inputStream = new InputStreamReader(connection.getInputStream()); 
       BufferedReader input = new BufferedReader(inputStream); 

       // get input 
       command = input.readLine(); 

       // process input 
       System.out.println("Command: " + command); 
       responseString = command + " MC2 It Works!"; 

       // get output handler 
       PrintStream response = new PrintStream(connection.getOutputStream()); 

       // send response 
       response.println(responseString); 
      } 
     } 
     catch (IOException e){ 
      e.printStackTrace(); 
     } 
    } 
} 

客戶:

class Client { 

    private $address; 
    private $port; 

    public function __construct($address, $port){ 
     $this->address = $address; 
     $this->port = $port; 
     $this->init(); 
    } 

    private function init(){ 

     //create socket 
     if(! $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'))){ 
      $this->showError("socket create"); 
     }; 

     //establish connection 
     socket_connect($socket, $this->address, $this->port); 

     //write to server 
     $message = "I am a client"; 
     socket_write($socket, $message, strlen($message)); //Send data 

     echo "Listening to Server\n"; 

     //read from server 
     if(!$reponse = socket_read($socket, 2048, PHP_NORMAL_READ)){ 
      $this->showError("socket read"); 
     } 

     //print response 
     echo "Response from server------------------\n"; 
     echo $reponse; 

     socket_close($socket); 

    } 

    private function showError($message){ 
     echo ("Error: ".$message); 
     exit(666); 

    } 

} 

$address="localhost";$port=9005; 
echo "Testing Client Server\n"; 
$client = new Client($address, $port); 

可能有人請指引我可能是什麼問題就在這裏?

回答

0

在服務器端,代碼期望一個線路(換行終止),在PHP你送

socket_write($socket, $message, strlen($message)); 

請檢查你相應地發送並確保您發送的換行字符的數據。

+0

謝謝奧茲根,那就是問題!服務器正在尋找最終線路! – 2015-04-06 10:36:33

相關問題