2012-11-13 97 views
1

問題如何獲得服務器消息正確

我發送消息「12345」從插座服務器到客戶端:

myPrintWriter.println("12345"); 

後,我閱讀客戶端此消息:

int c; 
while ((c = inputStream.read()) != -1) 
{ 
    byte[] buffer2 = new byte[1]; 
    buffer2[0] = (byte) c; 
    String symbol = new String(buffer2 , "UTF-8"); 
    String symbolCode = Integer.toString((int)buffer2[0]); 
    Log.v(symbol, symbolCode); 
} 
Log.v("c == -1", "Disconnected"); 

我在日誌中看到的東西: enter image description here

隨着

out.println("abcrefg"); 

enter image description here

爲什麼?我認爲這是線路終止符號。我需要正確地得到字符串「12345」或任何其他和下一個字符串。請幫幫我。


如果我使用bufferedReader.readLine():

try 
{ 
    byte[] b1 = new byte[1]; 
    int dataInt = clientSocket.getInputStream().read(); 
    b1[0] = (byte)dataInt; 

    final String data; 
    if(dataInt == -1) 
     connectionIsLost(); 

    if(dataInt != -1) 
    { 
     String c = new String(b1, "UTF-8"); 
     data = c + inToServer.readLine(); 
    } 
    else 
     data = inToServer.readLine(); 

    if (data != null) 
    { 
     Log.v("data", data); 
     runOnUiThread(new Runnable() 
     { 
      //data parsing 
     }); 
    } 
} 
catch (IOException e){...} 

如果我慢發送消息:

> V/data(5301): -3#Leo#alone in the dark 11-12 
> V/message(5301): Leo: alone in the dark 11-12 
> V/data(5301): -3#Leo#cgh 11-12 
> V/message(5301): Leo: cgh 11-12 
> V/data(5301): -3#Leo#c 
> V/message(5301): Leo: c 11-12 
> V/data(5301): -3#Leo#x 11-12 
> V/message(5301): Leo: x 
> V/data(5301): -3#Leo#d 11-12 
> V/message(5301): Leo: d 

但是,如果我做得更快:

> V/data(5512): -3#Leo#fccc 
> V/message(5512): Leo: fccc 
> V/data(5512): -3#Leo#ccc 
> V/data(5512): -3#Leo#cccc 
> V/message(5512): Leo: ccc 
> V/message(5512): Leo: cccc 
> V/data(5512): --3#Leo#cccc //<-----error 
> V/data(5512): 3-3#Leo#cccc //<-----error 
> V/data(5512): #Leo#xdd 

例外:(

回答

1

心目中的UTF-8 enconding可能會導致每個字符多個字節,以上代碼將不能正確地處理它們。

如果你想讀String編碼在UTF-8,最好是讓他們解碼'BufferdReader`並逐行獲取它。

示例代碼:

String line; 
    BufferedReader _in = new BufferedReader(new InputStreamReader(_socket.getInputStream(),"UTF-8")); 

    try { 
     while ((line = _in.readLine()) != null) { 
      Log.d(TAG, line); 
     } 
     Log.d(TAG, "Connection is closed"); 
    } catch (Exception e) { 
     Log.d(TAG, "Connection is closed"); 
    } 

問候。

+0

所以我不能看到我的連接狀態,當inputStream返回-1。 – Leo

+0

我不確定我是否理解了您的評論,但是使用上面的代碼,當緩衝區中沒有更多字符串時,您會得到'null'。如果你想檢查連接狀態,你仍然可以看看'InputStream'或'Socket'。 – Luis

+0

是的,我不能,但所以我創建了一些問題:InputStream.read()刪除我的InputStream的第一個字節。我試圖與其他行這個字節連接所有的罰款,但如果消息來的太快,由於某種原因,第一個字節不與其他線路拼接。之後,我收到一個例外。 – Leo

1

當然是CR/LF。 這是因爲您使用的是println。改爲嘗試print