JAVA program for online network speed testing (1): idea and console main program

Source: Internet
Author: User
Tags connect socket

Reason

Because the information authorities of higher-level companies are often complained that various business application systems reflect slow system usage, the problems are all attributed to poor network speed. The first part of the business system is deployed at the head office level, and many others are independently constructed by various business departments. They do not know where to find the various small companies and adopt the five-way technical routes, there is no uniform standard or technical platform, so the level is uneven. When there are few people, the system is slower as a snail bait. The network infrastructure has been transformed and upgraded almost in the past few years, and is a MB desktop and 1 GB backbone. Although local and municipal companies are scattered in their offices, they all use MPLSVPN technology, a gigabit backbone technology built using dedicated optical fiber cables for power supplies. local and provincial companies use dedicated optical fiber cables for gigabit or 10 Gigabit Networks. Therefore, the network infrastructure is more than enough. In order to prove his innocence, the higher-level authority developed the idea of building a hierarchical and distributed network speed test system. If you say that the network speed is slow, open the web page on the client and test the network speed at all levels, you may see whether the network speed is slow or the application system itself is too junk.


Ideas

The reference method provided on the network. Most of the WEB version is to download a large file from the client using JAVASCRIPT, and then get the network speed according to the speed = total downloads/time; the professional open-source testing tool is iperf and is of the c version. Compared with the amateur, the professional is more than just a little bit. Therefore, I learned about the basic idea and method of iperf, so I used JAVA to write and use socket to directly implement communication. The server and the client work together, the network speed is calculated based on the data volume and time of TCP communication. On the one hand, the efficiency is high, and other factors such as HTTP protocol and JAVASCRIPT loading and execution efficiency are reduced. On the other hand, the applet can be used to implement B/S applications, and the client is easy to deploy and use. The program code references JPerf. java of the JGroups project of OSCHINA. The project name is jperf, which is developed and tested using eclipse. At present, the basic functions are implemented because only verification is performed, so complete Exception Handling and verification are not performed ).


Program code jperf. java

Import java. io. *; import java.net. inetAddress; import java.net. serverSocket; import java.net. socket; import java.net. unknownHostException; import java. text. numberFormat;/*** Tool to measure TCP throughput, similar to iperf * @ author Bela Ban * @ version $ Id: JPerf. java, v 1.4 2007/12/28 23:29:17 belaban Exp $ */public class jperf implements Runnable {boolean client; boolean direction; // test direction: tr Ue-up test, false-down int num; InetAddress local_addr; int local_port; int remote_port; InetAddress remote_addr; int size; int receivebuf = 200000; int sendbuf = 200000; static NumberFormat f; socket client_sock; static {f = NumberFormat. getNumberInstance (); f. setGroupingUsed (false); f. setMaximumFractionDigits (2);} public jperf () {}// implement the Thread class interface Runnable, used to support multi-Thread @ Override public void run (){/ /TODO Auto-generated method stub try {server_accept_data ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (ClassNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace () ;}// used to call the public jperf (String remote_addr, int remote_port, int num, int size, boolean direction) throws UnknownHostException {this. remote_addr = InetAddress. GetByName (remote_addr); this. remote_port = remote_port; this. num = num; this. size = size; this. direction = direction;} private void start (boolean client, boolean direction, int num, int size, String local_addr, int local_port, String remote_addr, int remote_port, int receivebuf, int sendbuf) throws IOException, ClassNotFoundException {this. client = client; this. direction = direction; this. num = num; this. size = s Ize; this. local_addr = InetAddress. getByName (local_addr); this. local_port = local_port; this. remote_addr = InetAddress. getByName (remote_addr); this. remote_port = remote_port; this. receivebuf = receivebuf; this. sendbuf = sendbuf; if (client) {client () ;}else {server () ;}// the client calls public String client () throws IOException {System. out. println ("-- creating socket to" + this. remote_addr + ":" + this. remote_por T); client_sock = new Socket (this. remote_addr, remote_port); String result = ""; if (sendExchangeData () = true) {if (direction = true) result = sendData (num, size ); else result = receiveData (num, size);} else {result = "connect to server and exchange data fail! ";} System. out. println (result); client_sock.close (); return result;} // the client sends the test data parameter private boolean sendExchangeData () throws IOException {boolean ret = true; client_sock.setReceiveBufferSize (receivebuf); Response (sendbuf); ObjectOutputStream write = new ObjectOutputStream (new BufferedOutputStream (client_sock.getOutputStream (); write. writeObject (num); write. flush (); write. WriteObject (size); write. flush (); write. writeObject (direction); write. flush (); return ret;} // The server calls private void server () throws IOException, ClassNotFoundException {ServerSocket srv_sock = new ServerSocket (local_port, 10, this. local_addr); System. out. println ("-- waiting for client on" + srv_sock.getLocalSocketAddress (); while (true) {// wait for a client connect Socket client_sock = srv_sock.accept (); // Start a new thread deal this connection: jperf thread_client = new jperf (); thread_client.client_sock = client_sock; thread_client.sendbuf = sendbuf; Signature = receivebuf; // each client has a single Thread and supports simultaneous connection of multiple clients to thread Thread = new thread (thread_client); Thread. start () ;}// server receives and sends test data private void server_accept_data () throws IOException, ClassNotFoundException {client_sock.setReceiveBufferSiz E (receivebuf); client_sock.setSendBufferSize (sendbuf); System. out. println ("-- accepted data connection from" + response (); ObjectInputStream in = new ObjectInputStream (new BufferedInputStream (client_sock.getInputStream (); int num = 0, size = 0; boolean direction = false; num = (Integer) in. readObject (); size = (Integer) in. readObject (); direction = (Boolean) in. readObject (); if (num> 0 & & Size> 0) {String result; if (direction = true) result = receiveData (num, size); else result = sendData (num, size); System. out. println (result);} else {System. out. println ("-- invalid exchange data! ");} Client_sock.close ();} // sends data and calculates the test result private String sendData (int num, int size) throws IOException {System. out. println ("-- sending data to" + client_sock.getRemoteSocketAddress (). toString () + "total" + num + "messages"); DataOutputStream out = new DataOutputStream (new BufferedOutputStream (client_sock.getOutputStream ())); byte [] buf = new byte [size]; for (int I = 0; I <buf. length; I ++) buf [I] = (byte) (I % 128); long start = 0, stop; int cnt = 1; int incr = num/10; start = System. currentTimeMillis (); for (int I = 0; I <num; I ++) {out. write (buf, 0, buf. length); out. flush (); if (cnt % incr = 0) System. out. println ("-- sent" + cnt + "messages"); cnt ++;} stop = System. currentTimeMillis (); long diff = stop-start; String result = report ("send message to" + client_sock.getRemoteSocketAddress (). toString (), (long) num * (long) size, diff); return result;} // receives data and calculates the test result private String receiveData (int num, int size) throws IOException {System. out. println ("-- accepted data from" + client_sock.getRemoteSocketAddress (). toString () + "total" + num + "messages"); DataInputStream in = new DataInputStream (new BufferedInputStream (client_sock.getInputStream ())); byte [] buf = new byte [size]; long counter = 0; int incr = num/10; long start = 0, stop; while (true) {int len = in. read (buf, 0, buf. length); if (len <= 0) break; if (start = 0) start = System. currentTimeMillis (); counter + = len; if (counter/size) % incr = 0) System. out. println ("-- received" + counter/size);} stop = System. currentTimeMillis (); long diff = stop-start; String result = report ("received packets from" + client_sock.getRemoteSocketAddress (). toString (), counter, diff); return result;} // calculate the test result private String report (String direction, long totalbyte, double diff) {StringBuilder sb = new StringBuilder (); double tbs = totalbyte/(1024*1024); if (tbs <1000) sb. append ("\ n" + direction + ", total number of test data" + f. format (tbs) + "Mbyte" + ", in" + diff + "millisecond"); else {tbs = tbs/1024; sb. append ("\ n" + direction + ", total number of test data" + f. format (tbs) + "Gbyte" + "," + diff + "millisecond");} // tcp throughput: double throughput = totalbyte/(diff/1000.0)/1024.0; if (throughput <1, 1000) sb. append ("\ n network throughput:" + f. format (throughput) + "KB/second"); else {throughput/= 1024.0; sb. append ("\ n network throughput:" + f. format (throughput) + "MB/second");} // bandwidth double bandwidth = totalbyte/(diff/1000.0)/1024.0*8; if (bandwidth <1000) {sb. append ("\ n network bandwidth:" + f. format (bandwidth) + "Kb/second");} else {bandwidth/= 1024.0; if (bandwidth> 1000) {bandwidth/= 1024; sb. append ("\ n network bandwidth:" + f. format (bandwidth) + "Gb/second");} else sb. append ("\ n network bandwidth:" + f. format (bandwidth) + "Mb/second");} return sb. toString ();} static void help () {System. out. println ("JPerf [-help] [-client] [-direction <up | down>] [-num <number of msgs] [-size <bytes>] [-local_addr <interface>] [-local_port <port] "+" [-remote_addr <IP addr>] [-remote_port <port>] [-receivebuf <bytes>] [-sendbuf <bytes>] ");} // main program execution Entry public static void main (String [] args) throws UnknownHostException {boolean client = false; boolean direction = false; // test direction: true-up test, false-down test int num = 10000; int size = 8192; String local_addr = InetAddress. getLocalHost (). getHostAddress (); String remote_addr = local_addr; int local_port = 5000; int remote_port = 5000; int receivebuf = 200000, sendbuf = 200000; for (int I = 0; I <args. length; I ++) {if (args [I]. equals ("-client") {client = true; continue;} if (args [I]. equals ("-num") {num = Integer. parseInt (args [++ I]); continue;} if (args [I]. equals ("-size") {size = Integer. parseInt (args [++ I]); continue;} if (args [I]. equals ("-local_addr") {local_addr = args [++ I]; continue;} if (args [I]. equals ("-remote_addr") {remote_addr = args [++ I]; continue;} if (args [I]. equals ("-local_port") {local_port = Integer. parseInt (args [++ I]); continue;} if (args [I]. equals ("-remote_port") {remote_port = Integer. parseInt (args [++ I]); continue;} if (args [I]. equals ("-receivebuf") {receivebuf = Integer. parseInt (args [++ I]); continue;} if (args [I]. equals ("-sendbuf") {sendbuf = Integer. parseInt (args [++ I]); continue;} if (args [I]. equals ("-direction") {String value = args [++ I]; if (value. toLowerCase (). equals ("up") direction = true; else direction = false; continue;} help (); return ;}try {new jperf (). start (client, direction, num, size, local_addr, local_port, remote_addr, remote_port, receivebuf, sendbuf);} catch (IOException e) {e. printStackTrace ();} catch (ClassNotFoundException e) {e. printStackTrace ();}}}

Compile code: javac jperf. java

Run java jperf on the server. After it is started, it listens on port 5000 by default.

Run java jperf-client-remote_addr x on the client. x. x. x. The default parameter is 10000 data packets and 8192 data packet size for the default windows tcp Window). The port is 5000 and the direction is test downlink.

Java jperf-client-remote_addr x. x-direction up test the uplink.

After testing, two computers connected through a 11.3 Mbit/s switch have a throughput of 90.4 MB/s and a bandwidth of about Mbit/s.


This article from the "a programmer's Journey" blog, please be sure to keep this source http://hancool.blog.51cto.com/1836252/1352228

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.