2011-09-27 101 views
0

我在java中有一個java客戶端 - 服務器應用程序,它們都使用包含發送/接收消息的相同連接類。 出於某種原因,一些我發送的郵件的格式不正確的順序接收:java TCP套接字消息中斷

這裏的代碼

//set up 
_in = new BufferedReader(new InputStreamReader(this._socket.getInputStream())); 
_out = new BufferedWriter(new OutputStreamWriter(this._socket.getOutputStream())); 
this._socket.setSoTimeout(S_TIMEOUT); 


public synchronized boolean send(String message){ 
    try { 
     _out.write(message); 
     _out.write(Connection.DELIMITER); 
     _out.flush(); 
     return true; 
    } catch (IOException e) { 
    } 
    return false; 
} 


public String receive(){ 
    int c; 
    try { 
     String message = ""; 
     System.out.println("Getting message:"); 
     c = _in.read(); 
     while(c != -1 && c != Connection.DELIMITER) { 
      message += (char) c; 
      c = _in.read(); 
     } 
     if (c == -1) { 
      return null; 
     } 
     return message; 
    } catch (IOException e) { } 
    return null; 
} 

一些消息,例如「NEW_ORDER」將可能與「ew_ord」返回。 某些字符丟失,其他字符分開發送。這似乎很奇怪,因爲它的TCP

這可能是一個編碼相關的問題?

定界符是(炭)0 套接字超時是20000(即,20個senconds)。每10秒我發一個空的信息,以確保插座不關閉

編輯: 雖然它是使用掃描儀解決的,但我必須說,原始代碼在許多消息/各種機器上工作很長時間(幾個星期),然後突然無法在一臺特定的機器上使用一條特定的消息(其他消息經歷的很好)。我已經做了很多次在Java中的套接字數據傳輸,我寫了很多讀/寫方法來處理套接字。這是我第一次遇到這個問題。

儘管在原始代碼中我設置了編碼(在發佈的代碼中我沒有),但我相信問題是編碼相關的。在某一時刻,收到的信息每秒鐘都缺少一個字符。之後我改變了一下,並且在單獨的消息中收到了消息的第一/第二個字符。根據我的理解,這是一個編碼問題,或者是在消息發送者機器上運行的一些防火牆/其他安全程序,它決定對輸出數據包進行過濾。

+2

什麼是'Connection.DELIMITER'和'S_TIMEOUT'目前被定義爲? – cHao

+3

與您的問題無關,但我建議在收到消息時使用'StringBuilder',以提高效率。 –

回答

3

嘗試用掃描儀替換您的接收,並讓它爲您完成工作。

// in your setup 
Scanner sc = new Scanner(_in).useDelimiter(Connection.DELIMETER); 

public String receive() { 
    try { 
     return sc.next(); 
    } catch(IOException e) { 
     return ""; 
    } 

} 
+0

解決了它。非常感謝。 – galchen

0

對於初學者,我會確保您在這些catch塊中打印異常。

然後,您使用平臺默認編碼將字符轉換爲字節。如果這兩個進程在不同的機器上運行,那麼他們有可能使用不同的編碼。我會確保在設置Reader和Writer時指定編碼。

0

您可以使用UTF編碼獲取消息的完整字符串。

你可以試試這段代碼,我很確定關於這段代碼,因爲我在My Chat Application中使用它。

String data=" "; 

socket = new Socket("localhost",999); 
while(true) 
     { 
      dos = new DataOutputStream(socket.getOutputStream()); 
      dis = new DataInputStream(socket.getInputStream()); 
      data = dis.readUTF(); 
      jta.append(data +"\n"); 
     } 

其中jta是JTextArea。

它是客戶端

現在用於服務器端:

try 
{ 

server = new ServerSocket(999);  

Socket soc = server.accept(); 

     while(true) 
     { 
      String data=""; 
      try 
      {     
       dis = new DataInputStream(soc.getInputStream()); 
       dos = new DataOutputStream(soc.getOutputStream()); 
       data = dis.readUTF(); 
      } 
      catch(Exception e) 
      { } 
      jta.append(data + "\n"); 
     } 
    } 
    catch (IOException e) 
    { 
     JOptionPane.showMessageDialog(this, e); 
     System.exit(-1); 
    }