-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.cpp
84 lines (65 loc) · 1.93 KB
/
server.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "server.h"
#include <chrono>
server::server(int port) : port(port)
{
this->sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (this->sockfd == -1) {
perror("socket");
return;
}
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(port);
if ( bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) {
perror("bind");
close(sockfd);
return;
}
if (listen(sockfd, 5) == -1) {
perror("listen");
close(sockfd);
return;
}
cout << "Server is listening on port " << port << "..." << endl;
}
int server::StartRecv()
{
sockaddr_in clientAddr;
socklen_t clientLen = sizeof(clientAddr);
cout<<"Waiting for connection..."<<endl;
int client_sockfd = accept(sockfd, (struct sockaddr*)(&clientAddr), &clientLen);
if (client_sockfd == -1) {
perror("accept");
return 1;
}
cout<<"Accepted connection from "<<inet_ntoa(clientAddr.sin_addr)<<endl;
char buffer[1000];
this->recvKB = 0;
int bytes_received;
cout<<"Receiving data..."<<endl;
auto start_time = chrono::high_resolution_clock::now();
while((bytes_received = recv(client_sockfd, buffer, 1000, 0)) > 0)
{
this->recvKB+=bytes_received/1000.0;
}
if(bytes_received == -1){
perror("recv");
close(client_sockfd);
this->Close();
return 1;
}
auto end_time = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::milliseconds>(end_time-start_time).count();
this->Mbps = this->recvKB*8/1000/(duration/1000.0);
close(client_sockfd);
return 0;
}
void server::Close()
{
close(sockfd);
}
void server::PrintResult()
{
cout<<"Received="<<(int)this->recvKB<<" KB"<<" | Rate="<<this->Mbps<<" Mbps"<<endl;
}