测试网络带宽可以了解网络最大的传输速率并在实际的程序设计与测试过程中对自己的程序进行优化。
1、传输协议
1)客户端先发送如下结构体告知服务端接下来传输的数据长度以及次数
struct Message
{
int32_t length; //每个消息的长度
int32_t times; //发送次数
}__attribute__((__packed__));
2)服务端接受到上述的结构体之后开始计时,并在接下来的时间内接受times次length长的数据,并计算带宽。
2、服务端代码如下:
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <assert.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "common.h"
int recv_n(int fd, void* buff, int size)
{
int current = 0;
while(current < size)
{
size_t read_size = read(fd, buff, size-current);
assert(read_size != -1);
if(read_size == 0) //EOF
break;
current += read_size;
}
return current;
}
int main()
{
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
assert(listenfd >= 0);
struct sockaddr_in listen_addr;
memset(& listen_addr, 0, sizeof(sockaddr_in));
listen_addr.sin_family = AF_INET;
listen_addr.sin_port = htons(port);
listen_addr.sin_addr.s_addr = INADDR_ANY;
int ret = bind(listenfd, (struct sockaddr*)&listen_addr, sizeof(sockaddr));
assert(ret == 0);
ret = listen(listenfd, 10);
assert(ret==0);
socklen_t len;
int client_fd = accept(listenfd, NULL, &len);
assert(client_fd >=0);
//先接受Message结构体
struct Message msg={0,0};
int size = read(client_fd, &msg, sizeof(struct Message));
assert(size == sizeof(Message));
struct timeval begin_time;
gettimeofday(&begin_time, NULL);
char tmp_buff[msg.length];
int recv_count;
for(int i=0; i<msg.times; i++)
{
recv_count = recv_n(client_fd, tmp_buff, msg.length);
assert(recv_count == msg.length);
}
int mb = msg.times*msg.length/1024/1024;
struct timeval end_time;
gettimeofday(&end_time, NULL);
float speed = mb / ((unsigned int)end_time.tv_sec - (unsigned int)begin_time.tv_sec);
std::cout<<"transfer speed: "<< speed<<"mb/s"<<std::endl;
return 0;
}
3、客户端代码:
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include "common.h"
#include <iostream>
int main()
{
int client_fd = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("172.25.0.200");
server_addr.sin_port = htons(port);
int ret = connect(client_fd, (sockaddr*)&server_addr, sizeof(server_addr));
assert(ret == 0);
std::cout<<"Connected!"<<std::endl;
//先发送次数和大小
struct Message msg;
msg.length = 10*1024;
msg.times = 1024;
ret = write(client_fd, &msg, sizeof(Message));
assert(ret != -1);
char* ptr = (char*)malloc(msg.length*sizeof(char));
for(int i=0; i<msg.length; i++)
{
ptr[i] = 'a'+i%16;
}
for(int i=0; i<msg.times; i++)
{
write(client_fd, ptr, msg.length*sizeof(char));
}
close(client_fd);
free(ptr);
return 0;
}
4、运行结果
1)本机运行:
2)传到云服务器:
(单位应该是kib和mib才对!而且代码只是单向传输了数据。)