-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTCPSocket.cpp
53 lines (38 loc) · 1.06 KB
/
TCPSocket.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
#include "TCPSocket.h"
using namespace std;
unique_ptr<TCPSocket> TCPSocket::accept() {
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int td;
td=::accept(get_sd(), (struct sockaddr*)&client_addr, &client_len);
if (td < 0) {
perror("Error accepting");
exit(1);
}
return make_unique<TCPSocket>(td, client_addr);
}
void TCPSocket::send(std::string msg) {
if (::send(get_sd(),msg.c_str(), msg.size(), 0) < 0) {
cerr << "Error sending" << endl;
exit(1);
}
}
void TCPSocket::listen(int num_connections) {
// listens for incoming messages on given port
if (::listen(get_sd(), num_connections) < 0) {
perror("Error listening");
exit(1);
}
}
string TCPSocket::recv() {
string res;
int buf_len = 1024;
char buf[buf_len];
int len_recv = 0;
if ((len_recv = ::recv(get_sd(), buf, buf_len-1, 0)) > 0) {
buf[len_recv] = 0;
//assert(strlen(buf) == len_recv);
res += string(buf, len_recv);
}
return res;
}