2012-08-24 45 views
0

我創建的Java程序的一部分需要與遠程計算機上的服務對話。該遠程計算機正在Windows平臺上運行服務(用Delphi編寫)。如何使用Java套接字從遠程服務器讀取響應

我需要連接到該機器,發送命令字符串並接收(字符串)響應。

如果我連接使用Linux CLI telnet會話我得到預期的反應:

[[email protected] ~]$ telnet [host IP] [host port] 
Trying [host IP]... 
Connected to [host IP]. 
Escape character is '^]'. 
Welcome to MidWare server 
ping 
200 OK 
ProcessDownload 4 
200 OK 

在該行「平」和「ProcessDownload 4」我打字在終端上面,其他線路是從反應遠程系統。

我創造了我的Java類主要是做這項工作,調用相應的方法來嘗試和測試這個(我已經離開了無關緊要的東西):

public class DownloadService { 
    Socket _socket = null; // socket representing connecton to remote machine 
    PrintWriter _send = null; // write to this to send data to remote server 
    BufferedReader _receive = null; // response from remote server will end up here 


    public DownloadServiceImpl() { 
     this.init(); 
    } 

    public void init() { 
     int remoteSocketNumber = 1234; 
     try { 
      _socket = new Socket("1.2.3.4", remoteSocketNumber); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     if(_socket !=null) { 
      try { 
       _send = new PrintWriter(_socket.getOutputStream(), true); 
       _receive = new BufferedReader(new InputStreamReader(_socket.getInputStream())); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     }  
    } 
    public boolean reprocessDownload(int downloadId) { 
     String response = null; 
     this.sendCommandToProcessingEngine("Logon", null); 
     this.sendCommandToProcessingEngine("ping", null); 
     this.sendCommandToProcessingEngine("ProcessDownload",  Integer.toString(downloadId)); 
     try { 
      _socket.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return false; 
    } 
    private String sendCommandToProcessingEngine(String command, String param) { 
     String response = null; 
     if(!_socket.isConnected()) { 
      this.init(); 
     } 
     System.out.println("send '"+command+"("+param+")'"); 
     _send.write(command+" "+param); 
     try { 
      response = _receive.readLine(); 
      System.out.println(command+"("+param+"):"+response); 
      return response; 
     } catch (IOException e2) { 
      e2.printStackTrace(); 
     } 
     return response; 
    } 
    public static void main(String[] args) { 
     DownloadServiceImpl service = new DownloadServiceImpl(); 
     service.reprocessDownload(0); 
    } 


} 

正如你會在看到代碼,有幾個sys.out來指示程序何時試圖發送/接收數據。

輸出生成的:

send 'Logon(null)' 
Logon(null):Welcome to MidWare server 
send 'ping(null)' 

所以Java被連接到服務器確定以「歡迎使用中間件」的消息,但是當我嘗試發送一個命令(「中國平安」)我不得到迴應。

所以問題: - Java看起來是否正確? - 問題可能與字符編碼有關(Java - > windows)?

回答

1

您需要刷新輸出流:

_send.write(command+" "+param+"\n"); // Don't forget new line here! 
_send.flush(); 

,或者因爲你創建一個自動沖洗PrintWriter

_send.println(command+" "+param); 

後者的缺點是線路末端可以\n\r\n,具體取決於Java VM運行的系統。所以我更喜歡第一個解決方案。

+0

從服務器獲得更有用的響應,而不是我期待的響應,但我現在正在得到響應。乾杯。 – DaFoot

相關問題