2014-03-29 29 views
0

我將一些字節放入客戶端套接字OutputStream並將它們傳遞給服務器套接字時遇到問題。使用BufferedReader我想讀取這些字節,但方法read()獲取字符,所以當發送範圍爲<-128,-1>...時,我通常會得到不同的值。我如何將這些字符轉換爲我想要的字節。使用緩衝讀取器獲取不同的字節

public class Client { 

    public static void main(String[] args) { 
     Socket s = null; 
     InputStream is = null; 
     OutputStream os = null; 
     try { 
      s = new Socket("localhost", 3000); 
      is = s.getInputStream(); 
      os = s.getOutputStream(); 
      int read; 
      String str = ""; 
      while ((read = is.read()) != '\n') { 
       str += (char) read; 
      } 
      System.out.println(str); 
      ByteBuffer b = ByteBuffer.allocate(4); 
      b.order(ByteOrder.BIG_ENDIAN); 
      b.putInt(430); 
      byte[] message = b.array(); 
      for (int i = 0; i < message.length; i++) { 
       System.out.println(message[i] + " "); 
      } 
      os.write(message); 
     } catch (Exception ex) { 
     } 
    } 
} 



class Robot extends Thread { 

    private Socket s; 

    public static void main(String[] args) { 
     ServerSocket ss = null; 
     try { 
      ss = new ServerSocket(3000); 
      while (true) { 
       Socket s = ss.accept(); 
       Robot srv = new Robot(); 
       srv.s = s; 
       srv.start(); 
      } 

     } catch (NumberFormatException numberEx) { 
      System.out.println("Port of port is not integer"); 
     } catch (IOException ioEx) { 
      System.out.println("Input connection problem"); 
     } finally { 
      try { 
       ss.close(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
       Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex); 
      } 
     } 
    } 

    @Override 
    public void run() { 
     BufferedReader is = null; 
     OutputStream os = null; 
     try { 
      is = new BufferedReader(new InputStreamReader(s.getInputStream())); 
      os = s.getOutputStream(); 
      os.write("Send me data:\n".getBytes()); 
      int b; 
      while ((b = is.read()) != -1) { 
       System.out.println((byte) b + " "); 
      } 
     } catch (Exception ex) { 
     } 
    } 
} 
+4

不要使用閱讀器來讀取的字節。使用InputStream。讀者/作家是爲人物。 InputStream/OutputStream用於字節。 –

+0

@JBNizet是對的;看到[這裏](http://fgaliegue.blogspot.com/2014/03/strings-characters-bytes-and-character.html)是什麼,因爲這是一個普遍的Java誤解,「一個字符是兩個字節「 - 它真的不是 – fge

+0

同上。只需從'InputStream'直接讀取你的字節即可。請勿在名稱中使用'InputStreamReader'或'BufferedReader'或任何其他具有'Reader'的類。 –

回答

0

閱讀器將收到的字節轉換爲字符並使用系統屬性file.encoding(您可以更改它)。

如果您需要字符(字符串),您必須使用已知編碼(例如UTF-8)以字節爲單位對其進行解碼和編碼。它應該(必須)在客戶端和服務器上相同。

如果你只需要字節(字符,不字符串),你應該只使用流 - 沒有讀者

相關問題