2013-04-30 78 views
0

發送這是我的客戶端代碼無法讀取數量與DataOutputStream聯合

Random rand = new Random(); 
int n = rand.nextInt(50) + 1; 
DataInputStream dis = new DataInputStream(_socket.getInputStream()); 
DataOutputStream dos = new DataOutputStream(_socket.getOutputStream()); 
dos.writeInt(n); 

,這是服務器端的代碼

try { 
    DataInputStream dis = new DataInputStream(socket.getInputStream()); 
    BufferedReader input = new BufferedReader(new InputStreamReader(dis)); 
    int fromClient = input.read(); 
    System.out.println(fromClient); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

但我不fromClient recive任何東西,即使我chnage它這樣

System.out.println(fromClient+"test"); 

我沒有得到結果

回答

1

客戶端需要調用dos.flush()dos.close()來將緩衝的數據推送到服務器。 (如果你打算寫入更多的數據,然後刷新,否則關閉。)

服務器端需要使用實例上的readInt讀取數據。應使用DataInputStream讀取使用DataOutputStream編寫的數據。

最後,擺脫BufferedReader/InputStreamReader。這是錯誤的。

1

如果您在寫入端使用writeInt(),則應在讀取端使用readInt()(所有方法名稱與DataOutputStream和DataInputStream相關,請閱讀javadoc)。