views:

37

answers:

1

Does anyone have any tips on how to calculate the bandwidth usage of a socket?

For example, as I send data over a socket to the server I am connected to, I want to show the Kb/s that is being sent.

Google search didn't reveal anything useful. Maybe I'm searching the wrong terms.

+2  A: 

The best you're probably going to be able to easily do is to record when you start writing and then count bytes you've successfully sent to the Socket.getOutputStream.write() method. For a small amount of data, that will be very inaccurate as it's just filling up the OS's transmission buffer which will initially take bytes much faster than it actually sends them.

It should amortize to essentially the correct rate over a fairly large amount of data, however.

Mark Peters
This would work in theory, but it wouldn't provide a very accurate representation of the transfer speed at the current moment.For example: If I was logging for 5 mins... spent the first 2.5 mins doing nothing, and the last 2.5 mins sending 100kb/s. At the end of the 5 mins it would tell me the speed was 50kb/s average.I'm not looking for average speed since I began transmitting.I'm looking for current speed. Maybe the average of the last 5 seconds would work, but I have no idea to go about recording something like that.
EvilToast
That's called a moving average: http://en.wikipedia.org/wiki/Moving_average. It's pretty simple to calculate though there are various methods. There's really no such thing as calculating the bandwidth at any given moment; since data is discrete you have to have an average. One extremely simple method would be `average = (average + new_measurement_average) / 2.0`.
Mark Peters