简体   繁体   中英

Measure Size of Data Sent over Socket

I was thinking about how you would read how much data you send over a Socket. For example if I made a Chat Application and then wanted to find out how much a message would take (in kilobytes or bytes), how would I measure this?

I send a message like "Hello, world!". How do I measure the amount of bandwidth that would take to send?

I know there are programs to monitor how much data is sent and received over the wire and all that, but I wanted to try and do this myself to learn some.

Wrap the socket's output stream in a CountingOutputStream :

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

If you send raw string with no header (protocol) For the strings you have

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

For showing progress to user when sending files you can do this

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);
}

well, thats just a very simple implementation not using a buffer to read and send the data just for you get the idea. the method nitify.... would show in the GUI thread (not this one) the bytesSent value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM