I'm Shendi
最近搞了台服务器,于是就想测试一下网速(与用户之间的速度)
上传速度 客户端发数据给服务端,服务端接收到多少字节就是速度
下载速度 服务端发数据给客户端,客户端接收到多少字节就是速度
避免偏差过大,两个步骤执行时间都为10秒
代码如下
package shendi.test.dos;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 网速测试
* @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a>
* @version 1.0
*/
public class NetSpeed {
public volatile static boolean upYes;
public volatile static boolean downYes;
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(80);
new Thread(() -> {
try {
Socket socket = new Socket("公网ip地址",80);
OutputStream output = socket.getOutputStream();
while (true) {
if (upYes) {
output.write(-1);
break;
}
output.write(1);
}
InputStream input = socket.getInputStream();
int downNum = 0;
while (true) {
if (downYes) {
break;
}
input.read();
++downNum;
}
System.out.println("下载速度:" + (downNum / 10 >> 10) + "kb/s");
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
Socket socket = server.accept();
// 计时 十秒一次
new Thread(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
upYes = true;
System.out.println("上传测试已完成");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
downYes=true;
System.out.println("下载测试已完成");
}).start();
//服务端处理
InputStream input = socket.getInputStream();
int upNum = 0;
while (true) {
if (upYes) {
break;
}
input.read();
++upNum;
}
System.out.println("上传速度:" + (upNum / 10 >> 10) + "kb/s");
OutputStream output = socket.getOutputStream();
while (true) {
if (downYes) {
output.write(-1);
break;
}
output.write(1);
}
server.close();
}
}