-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
202 lines (175 loc) · 7.47 KB
/
Copy pathserver.cpp
File metadata and controls
202 lines (175 loc) · 7.47 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#include <iostream>
#include <vector>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/epoll.h>
const int MAX_EVENTS = 64;
const int PORT = 8080;
const int BUFFER_SIZE = 1024;
// Take current socket settings
// Add NONBLOCK flag
// Save settings
bool set_non_blocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) return false;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0;
}
int main() {
// 1. Create listening socket
// socket(int domain, int type, int protocol);
// AF_INET = IPv4, SOCK_STREAM = TCP, 0 = default protocol no.
// this will return 0, 1, 2, 3 or -1, significance:
// 0 -> stdin
// 1 -> stdout
// 2 -> stderr
// 3 -> socket
// -1 -> socket creation fails
int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd == -1) {
std::perror("Socket creation failed");
return 1;
}
// Allow immediate reuse of local address/port
// you tell the kernel, "Allow me to reuse this port immediately.""
int opt = 1; // opt = 1 means allow, opt = 0 means dont allow
setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
// 2. Bind to port
sockaddr_in server_addr{}; // A structure used to store an IPv4 address and port.
server_addr.sin_family = AF_INET; // Address Family = IPv4
server_addr.sin_addr.s_addr = INADDR_ANY; // Specifying IP Address, INADDR_ANY = 0.0.0.0 i.e. accept connections on all network interfaces
// WiFi → 192.168.1.10
// Ethernet → 10.0.0.5
// Loopback → 127.0.0.1
// INADDR_ANY will listen for all at once
server_addr.sin_port = htons(PORT); // htons means host to network short, converts 8080 into proper network byte order.
// now, server_addr looks like:
// Family = AF_INET
// IP = 0.0.0.0
// Port = 8080
// socket() -> creates socket object, bind() -> assigns address to socket
if (bind(listen_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
std::perror("Bind failed");
return 1;
}
// 3. Listen for incoming connections
// SOMAXCONN -> Controls the connection queue size.
// explanation: client1, client2, client3 sends connection request.
// Before server accepts, it temporarily stores these requests in queue.
// So, SOMAXCONN means -> use the maximum queue size allowed by the OS, instead of hard coded value
// Return value is 0 for success, -1 for failure
if (listen(listen_fd, SOMAXCONN) < 0) {
std::perror("Listen failed");
return 1;
}
// Need for non blocking socket:
// blocking socket waits forever unless there are no clients.
// for non-blocking -> if no clients then return immediately
if (!set_non_blocking(listen_fd)) {
std::perror("Failed to set non-blocking on listen socket");
return 1;
}
std::cout << "Server starting on port " << PORT << "...\n";
// epoll
// ↓
// Tell me which sockets are ready
// ↓
// Process only those sockets
int epoll_fd = epoll_create1(0);
if (epoll_fd == -1) {
std::perror("epoll_create1 failed");
return 1;
}
// Add listening socket to epoll instance
epoll_event ev{};
ev.events = EPOLLIN; // Watch for read events (new connections)
ev.data.fd = listen_fd;
// Monitor this socket and notify me when something interesting happens.
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listen_fd, &ev) == -1) {
std::perror("epoll_ctl failed for listen_fd");
return 1;
}
std::vector<epoll_event> events(MAX_EVENTS);
// 5. Core event loop
while(true) {
// Block until events occur (timeout = -1 means infinite wait)
// epoll_wait() puts your program to sleep until something happens.
// 4th parameter = -1, which means wait forever
int num_events = epoll_wait(epoll_fd, events.data(), MAX_EVENTS, -1); // Put my server to sleep until at least one event occurs.
if (num_events == -1) {
std::perror("epoll_wait failed");
break;
}
for(int i=0; i<num_events; ++i) {
int current_fd = events[i].data.fd;
// Scenario A: New Client connection on listening socket
// listen_fd = Reception Desk
// Client arrives
// ↓
// accept()
// ↓
// client_fd = Private room for that client
if (current_fd == listen_fd) {
sockaddr_in client_addr{};
socklen_t client_len = sizeof(client_addr);
// creates a new socket dedicated to that client.
int client_fd = accept(listen_fd, (struct sockaddr*)&client_addr, &client_len);
if (client_fd == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
std::perror("Accept error");
}
continue;
}
set_non_blocking(client_fd);
// Start monitoring this client socket too.
// Watch this client socket for incoming data (EPOLLIN)
// Using Edge-Triggered (EPOLLET) mode for optimal performance (Notifies ONLY once "data has arrived")
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = client_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client_fd, &ev) == -1) {
std::perror("epoll_ctl ADD client failed");
close(client_fd);
} else {
std::cout << "Connected new client (FD: " << client_fd << ")\n";
}
}
// Scenario B: Existing client sent data
else if (events[i].events & EPOLLIN) {
char buffer[BUFFER_SIZE];
bool close_connection = false;
// Since we use Edge-Triggered mode, we must loop and read ALL data
while (true) {
std::memset(buffer, 0, sizeof(buffer));
ssize_t bytes_read = read(current_fd, buffer, sizeof(buffer) - 1);
if (bytes_read > 0) {
std::cout << "[FD " << current_fd << "] Echoing: " << buffer;
// Simple echo response for Phase 1
write(current_fd, buffer, bytes_read);
} else if (bytes_read == 0) {
// Client closed connection cleanly
close_connection = true;
break;
} else {
// If errno is EAGAIN, it means we read all available data for now
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
std::perror("Read error");
close_connection = true;
break;
}
}
if (close_connection) {
std::cout << "Client disconnected (FD: " << current_fd << ")\n";
epoll_ctl(epoll_fd, EPOLL_CTL_DEL, current_fd, nullptr);
close(current_fd);
}
}
}
}
close(listen_fd);
close(epoll_fd);
return 0;
}