統計所有連接埠的 接受 與 發送 的流量。
:
源碼:
NetWork.java 用於計算連接埠的流量值.
NetWorkThread.java 線程類,用於將資訊顯示到介面中
import java.io.BufferedReader;<br />import java.io.InputStreamReader;<br />public class NetWork {<br />public String recevied;<br />public String sent;<br />public void NetWorkFlux(String cmdline) {<br />try {<br />String line;<br />Process p = Runtime.getRuntime().exec(cmdline);<br />BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));<br />int c = 0;<br />while ((line = input.readLine()) != null ) {</p><p>if(c > 3)<br />{<br />String s [] = line.replaceAll("Bytes", "").trim().replace(" ", "@").split(" ");<br />//System.out.println(s.length);</p><p>for(String str : s)<br />{<br />recevied = str.substring(0, str.indexOf("@"));<br />sent = str.substring(str.lastIndexOf("@") + 1, str.length());<br />}<br />/**System.out.println(recevied + " " + sent);<br />System.out.println("接受流量:" + Long.parseLong(recevied) / 1024 / 1024 + "MB");<br />System.out.println("發送流量:" + Long.parseLong(sent) / 1024 / 1024 + "MB");<br />**/<br />recevied = Long.parseLong(recevied) / 1024 + " KB";<br />sent = Long.parseLong(sent) / 1024 + " KB";<br />break;<br />}<br />c ++;<br />}<br />input.close();<br />} catch (Exception err) {<br />}<br />}<br />}<br />
import java.awt.Color;<br />import java.awt.GridLayout;<br />import javax.swing.JFrame;<br />import javax.swing.JLabel;<br />import javax.swing.JPanel;<br />public class NetWorkThread extends JFrame implements Runnable{<br />NetWork netWork = new NetWork();</p><p>private String recevied;<br />private String sent;</p><p>private JLabel lab1 = new JLabel("接受流量:");<br />private JLabel lab2 = new JLabel();<br />private JLabel lab3 = new JLabel("發送流量:");<br />private JLabel lab4 = new JLabel();</p><p>private JPanel p1 = new JPanel();<br />private JPanel p2 = new JPanel();<br />private JPanel p = new JPanel();</p><p>public NetWorkThread() {</p><p>p1.add(lab1);<br />p1.add(lab2);<br />p2.add(lab3);<br />p2.add(lab4);<br />p1.setBackground(Color.PINK);<br />p2.setBackground(Color.YELLOW);<br />p.add(p1);<br />p.add(p2);<br />p.setLayout(new GridLayout(2, 1));<br />this.setTitle("流量計算");<br />this.add(p);<br />this.setSize(200,100);<br />this.setResizable(false);<br />this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);<br />this.setVisible(true);</p><p>}</p><p>public void run() {<br />do<br />{<br />netWork.NetWorkFlux("netstat -e");<br />this.recevied = netWork.recevied;<br />this.sent = netWork.sent;<br />lab2.setText(recevied);<br />lab4.setText(sent);</p><p>try {<br />Thread.sleep(100);<br />} catch (InterruptedException e) {<br />e.printStackTrace();<br />}<br />}while(true);<br />}<br />public static void main(String[] args) {<br />new Thread(new NetWorkThread()).start();<br />}<br />}<br />