-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcp_server.cpp
More file actions
178 lines (156 loc) · 5.41 KB
/
tcp_server.cpp
File metadata and controls
178 lines (156 loc) · 5.41 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h> // read, write, close
#include <errno.h>
#include <fcntl.h>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cassert>
/*
struct in_addr {
uint32_t s_addr; // IPv4 in big-endian
};
struct sockaddr_in {
uint16_t sin_family; // AF_INET
uint16_t sin_port; // port in big-endian
struct in_addr sin_addr; // IPv4
};
// for IPv6 use sockaddr_in6
struct in6_addr {
uint8_t s6_addr[16]; // IPv6
};
struct sockaddr_in6 {
uint16_t sin6_family; // AF_INET6
uint16_t sin6_port; // port in big-endian
uint32_t sin6_flowinfo; // ignore
struct in6_addr sin6_addr; // IPv6
uint32_t sin6_scope_id; // ignore
};
*/
static void msg(const char *msg) {
fprintf(stderr, "%s\n", msg);
}
static void die(const char *msg) {
int err = errno;
fprintf(stderr, "[%d] %s\n", err, msg);
abort();
}
static void fd_set_nonblock(int fd) {
int flags = fcntl(fd, F_GETFL, 0); // get the flags
flags |= O_NONBLOCK; // modify the flags
fcntl(fd, F_SETFL, flags); // set the flags
// TODO: handle errno
}
// Step 6: Read & write
/* read/write can return less than the requested number of bytes under normal conditions
To actually read/write n bytes from/to a TCP socket. You must do it in a loop.
*/
static int32_t read_full(int fd, char *buf, size_t n) {
while (n > 0) {
ssize_t rv = read(fd, buf, n); // read can also be interrupted by a signal because it must wait if the buffer is empty.
if (rv < 0 && errno == EINTR) { // In this case, 0 bytes are read, but the return value is -1 and errno is EINTR. This is not an error.
continue;
}
else if (rv <= 0) {
return -1; // error, or unexpected EOF
}
assert((size_t)rv <= n);
n -= (size_t)rv;
buf += rv;
}
return 0;
}
static int32_t write_all(int fd, const char *buf, size_t n) {
while (n > 0) {
ssize_t rv = write(fd, buf, n);
if (rv <= 0) {
return -1; // error
}
assert((size_t)rv <= n);
n -= (size_t)rv;
buf += rv;
}
return 0;
}
const size_t k_max_msg = 4096;
static int32_t one_request(int connfd) {
// 1st we read in the msg
// 4 byte header
char rbuf[4 + k_max_msg];
errno = 0;
int32_t err = read_full(connfd, rbuf, 4); // rbuf == &rbuf[0]
if (err) { // zero == false
msg(errno == 0 ? "EOF" : "read() error");
return err;
}
uint32_t len = 0;
memcpy(&len, rbuf, 4); // assume little endian. Each message consists of a 4-byte little-endian integer indicating the length of the request and the variable-length payload.
if (len > k_max_msg) {
msg("too long");
return -1;
}
// request body
err = read_full(connfd, &rbuf[4], len);
if (err) {
msg("read() error");
return err;
}
// do something
printf("client says: %.*s\n", len, &rbuf[4]);
// reply using some protocol
const char reply[] = "world";
char wbuf[4 + sizeof(reply)];
len = (uint32_t)strlen(reply);
memcpy(wbuf, &len, 4); // &wbuf[0], remember the 1st 4 bytes indicates length of the msg
memcpy(&wbuf[4], reply, len);
return write_all(connfd, wbuf, 4+len);
}
int main() {
// Step 1: Obtain a socket handle
int fd = socket(AF_INET, SOCK_STREAM, 0);
// Step 2: Set socket options
int enable = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
// Step 3: Bind to an address
struct sockaddr_in addr {};
addr.sin_family = AF_INET;
addr.sin_port = htons(1234); // port
addr.sin_addr.s_addr = htonl(0); // wildcard IP 0.0.0.0
int rv = bind(fd, (const struct sockaddr *)& addr, sizeof(addr)); // struct sockaddr_in and struct sockaddr_in6 have different sizes, so the struct size (addrlen) is needed.
if (rv) { die("bind()"); }
// Step 4: Listen
rv = listen(fd, SOMAXCONN); // listening socket is created here. The OS will automatically handle TCP handshakes and place established connections in a queue.
if (rv) { die("listen()"); }
// Step 5: Accept connections
while (true) {
//accept
struct sockaddr_in client_addr {};
socklen_t addrlen = sizeof(client_addr);
int connfd = accept(fd, (struct sockaddr *)&client_addr, &addrlen);
if (connfd < 0) {
continue; // error
}
// only serves one client connection at once
while (true) {
int32_t err = one_request(connfd);
if (err) {
break;
}
}
close(connfd);
/*
want_read = [...] # socket fds
want_write = [...] # socket fds
can_read, can_write = wait_for_readiness(want_read, want_write) # blocks!
for fd in can_read:
data = read_nb(fd) # non-blocking, only consume from the buffer
handle_data(fd, data) # application logic without IO
for fd in can_write:
data = pending_data(fd) # produced by the application
n = write_nb(fd, data) # non-blocking, only append to the buffer
data_written(fd, n) # n <= len(data), limited by the available space
*/
}
return 0;
}