2011-12-09 13 views

回答

1

這可以通過裝飾套接字的輸入和輸出流來實現。

因此,它可能是這樣的:

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 
} 

也可以看看herehere

最後,如果您只想知道流量,可以使用嗅探器。

相關問題