2

Does anyone knows how to do this? using the java sockets

akf
  • 38,619
  • 8
  • 86
  • 96

1 Answers1

1

This can be achieved by decorating socket's input and output streams.

So it might look like this:

class SocketWrapper extends Socket {
    private CountingInputStream input;

    @Override
    public InputStream getInputStream() throws IOException {
        if (input == null) {
            input = new CountingInputStream(super.getInputStream());
        }

        return input;
    }

    public int getInputCounter() {
        return input.getCounter();
    }

    // other stuff like getOutputStream
}

class CountingInputStream extends InputStream {
    private final InputStream inputStream;

    public CountingInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    private int counter = 0;

    public int getCounter() {
        return counter;
    }

    @Override
    public int read() throws IOException {
        counter++;
        return inputStream.read();
    }

    // other methods
}

Also have a look here and here.

And finally, if you just want to know the amount of traffic, you may use sniffers.

Alexey Grigorev
  • 2,415
  • 28
  • 47