2012-12-14 49 views
0

我在想你會怎麼看你有多少數據傳送過來的插座。例如,如果我創建了一個聊天應用程序,然後想要知道消息需要多少(以千字節或字節爲單位),那麼我將如何度量呢?測量尺寸發送過插座

我發送消息,如「你好,世界!」。我如何衡量發送帶寬的數量?

我知道有一些程序來監視多少數據被髮送並通過導線和所有收到的,但我想嘗試做這一點我自己,學習一些。

回答

2

裹在插座的輸出流CountingOutputStream

CountingOutputStream cos = new CountingOutputStream(socket.getOutputStream()); 
cos.write(...); 
System.out.println("wrote " + cos.getByteCount() + " bytes"); 
+0

這是相當整潔。 – OmniOwl

0

如果您發送無標題(協議)原始字符串 對你有

String hello = "Hello World"; 
hello.getBytes().length //size of the message 

的字符串發送文件時,你可以做到這一點

Socket s = new Socket(); 
//connect to the client, etc... 

//supose you have 5 MB File 
FileInputStream f = new FileInputStream(myLocalFile); 

//declare a variable 
int bytesSent = 0; 
int c; 
while((c = f.read()) != -1) { 
    s.getOutputStream().write(c); 
    bytesSent++; //One more byte sent! 
    notifyGuiTotalBytesSent(bytesSent); 
} 

以及顯示用戶的進步,這就是隻是一個非常簡單的實現,不使用緩衝區來讀取和發送數據,只是爲您提供了想法。 方法nitify ....會顯示在GUI線程(不是這一個)bytesSent值

+0

如果我用什麼PrintWriter對象發送一些東西給服務器? – OmniOwl

+0

然後,你將在發送之前測量信息/文件的大小.. – fredcrs

+0

你應該調用String.getBytes()時,幾乎總是指定字符編碼......和大多數情況下,「UTF-8」是一個很好的編碼使用。 – dnault