-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSocket.cpp
95 lines (83 loc) · 1.77 KB
/
Socket.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
85
86
87
88
89
90
91
92
93
94
95
#include "Socket.h"
#include <iostream>
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#include <sys/types.h>
Socket::Socket() : is_initialized_(false), nagle_(NAGLE_ON) { }
Socket::~Socket() {
if (is_initialized_) {
Close();
}
}
int Socket::Send(char *buffer, int size, int flags) {
int bytes_written = 0;
int offset = 0;
while (size > 0) {
bytes_written = send(fd_, buffer + offset, size, flags);
if (bytes_written < 0) {
/*
if (errno == EAGAIN || errno == EWOULDBLOCK) {
perror("ERROR: send retry");
continue;
}
*/
// perror("ERROR: failed to send");
Close();
return 0;
}
size -= bytes_written;
offset += bytes_written;
assert(size >= 0);
}
return 1;
}
int Socket::Recv(char *buffer, int size, int flags) {
int bytes_read = 0;
int offset = 0;
while (size > 0) {
bytes_read = recv(fd_, buffer + offset, size, flags);
if (bytes_read <= 0) {
/*
if (errno == EAGAIN || errno == EWOULDBLOCK) {
//perror("ERROR: recv retry");
continue;
}
*/
// perror("ERROR: failed to recv");
Close();
return 0;
}
assert(bytes_read != 0);
size -= bytes_read;
offset += bytes_read;
assert(size >= 0);
}
return 1;
}
int Socket::NagleOn(bool on_off) {
nagle_ = (on_off ? NAGLE_ON : NAGLE_OFF);
int result = setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY,
(void *) &nagle_, sizeof(int));
if (result < 0) {
perror("ERROR: setsockopt failed");
return 0;
}
return 1;
}
bool Socket::IsNagleOn() {
return (nagle_ == NAGLE_ON) ? true : false;
}
void Socket::Close() {
shutdown(fd_, SHUT_RDWR);
close(fd_);
//perror("Socket closed");
is_initialized_ = false;
}