2012-03-01 48 views
0

我已經寫了一個客戶端Java應用程序,它通過HTTP與PHP服務器進行通信。我需要在java(客戶端)端實現一個監聽器來響應php服務器發出的請求。目前,java應用程序正在每分鐘更新一次的服務器上創建一個文本文件。java php通信

這工作正常,但現在客戶端Java應用程序的數量正在上升,這個原始系統開始崩潰。

改變這種情況的最好方法是什麼?我在java客戶端應用程序上嘗試了一個java ServerSocket監聽器,但無法使其工作。我無法完成溝通。 Web上的所有示例都使用localhost作爲ip地址示例,並且我的php服務器是遠程託管的。

我是否需要獲取客戶端計算機的IP地址並將其發送到PHP服務器,以便PHP知道在哪裏發送消息?這裏是java代碼...這是所有網站上...

public class MyJavaServer 
{ 

    public static void main(String[] args) 
    { 


     int port = 4444; 
     ServerSocket listenSock = null; //the listening server socket 
     Socket sock = null;   //the socket that will actually be used for communication 

     try 
     { 

      System.out.println("listen"); 
      listenSock = new ServerSocket(port); 

      while (true) 
      { 

       sock = listenSock.accept(); 

       BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream())); 
       BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())); 
       String line = ""; 
       while ((line = br.readLine()) != null) 
       { 
        bw.write("PHP said: " + line + "\n"); 
        bw.flush(); 
       } 

       //Closing streams and the current socket (not the listening socket!) 
       bw.close(); 
       br.close(); 
       sock.close(); 
      } 
     } 
     catch (IOException ex) 
     { 
      System.out.println(ex); 
     } 
    } 
} 

...這裏是PHP

$PORT = 4444; //the port on which we are connecting to the "remote" machine 
$HOST = "ip address(not sure here)"; //the ip of the remote machine(of the client java app's computer??? 

$sock = socket_create(AF_INET, SOCK_STREAM, 0) 
     or die("error: could not create socket\n"); 

$succ = socket_connect($sock, $HOST, $PORT) 
     or die("error: could not connect to host\n"); 

$text = "Hello, Java!\n"; //the text we want to send to the server 

socket_write($sock, $text . "\n", strlen($text) + 1) 
     or die("error: failed to write to socket\n"); 

$reply = socket_read($sock, 10000, PHP_NORMAL_READ) 
     or die("error: failed to read from socket\n"); 

echo $reply; 

這根本不起作用。 java應用程序偵聽,但php腳本從不連接。

此外,這是我的需求最好的方法? 謝謝。

+0

您是否檢查過是否有防火牆阻止傳入的請求? – Asaph 2012-03-01 04:21:16

+0

它是我家的電腦。我正在通過普通的無線路由器。順便說一句,如果防火牆要殺死這個,那麼它可能是錯誤的路要走。我的客戶不懂技術,我需要爲用戶提供簡單的解決方案。 – rob345 2012-03-01 04:24:49

+0

您可能有防火牆阻止訪問。它可能位於電纜調制解調器級別和/或更上游。是的,防火牆可能會成爲您設計中的障礙。你應該重新考慮設計。而不是將數據推送到客戶端,使客戶端輪詢服務器以獲取更新。 – Asaph 2012-03-01 04:55:11

回答

0

如果php服務器機器可以連接到java客戶端機器,那麼包含的代碼就可以工作。在你的情況下,這是遍佈整個網絡,這意味着Java客戶機應該有一個公衆可以訪問的IP。一旦擁有它,將該IP分配給$ HOST,然後代碼將正常運行。

假設沒有客戶端可以擁有公共IP,我認爲最好的方法是使您的java客戶端以HTTP請求的請求 - 回覆方式與您的PHP服務器對話。 Java客戶端像Web瀏覽器一樣發送HTTP請求並接收包含您的Java客戶端所需數據的HTTP回覆。當客戶端數量上升到PHP服務器無法處理的水平時,您可以將其擴展。儘管我自己沒有經驗,但現在擴展PHP服務器並不罕見。