MayaFlux 0.2.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches

◆ server_loop()

void Lila::Server::server_loop ( const ServerThread::StopToken stop_token)
private

Main server loop; accepts and manages clients.

Parameters
stop_tokenToken to signal server shutdown

Definition at line 194 of file Server.cpp.

196{
197 while (!stop_token.stop_requested() && m_running) {
198 fd_set readfds;
199 FD_ZERO(&readfds);
200 FD_SET(m_server_fd, &readfds);
201
202 timeval timeout { .tv_sec = 1, .tv_usec = 0 };
203
204#ifdef MAYAFLUX_PLATFORM_WINDOWS
205 int activity = select(0, &readfds, nullptr, nullptr, &timeout); // nfds ignored on Windows
206#else
207 int activity = select(m_server_fd + 1, &readfds, nullptr, nullptr, &timeout);
208#endif
209
210 if (activity < 0) {
211 int code = socket_errno();
212#ifndef MAYAFLUX_PLATFORM_WINDOWS
213 if (code == EINTR)
214 continue;
215#endif
216 if (m_running) {
217 LILA_ERROR(Emitter::SERVER, "Select error: " + socket_error_string(code));
218 }
219 break;
220 }
221
222 if (activity == 0)
223 continue;
224
225 sockaddr_in client_addr {};
226 socklen_t client_len = sizeof(client_addr);
227
228#ifdef MAYAFLUX_PLATFORM_WINDOWS
229 SOCKET client_socket = accept(static_cast<SOCKET>(m_server_fd), reinterpret_cast<sockaddr*>(&client_addr), &client_len);
230 int client_fd = static_cast<int>(client_socket);
231 if (client_socket == INVALID_SOCKET) {
232 int code = socket_errno();
233 if (code == WSAEWOULDBLOCK)
234 continue;
235 if (m_running) {
236 LILA_ERROR(Emitter::SERVER, "Accept failed: " + socket_error_string(code));
237 }
238 continue;
239 }
240#else
241 int client_fd = accept(m_server_fd, reinterpret_cast<sockaddr*>(&client_addr), &client_len);
242 if (client_fd < 0) {
243 if (errno == EAGAIN || errno == EWOULDBLOCK)
244 continue;
245 if (m_running) {
246 LILA_ERROR(Emitter::SERVER, "Accept failed: " + std::string(strerror(errno)));
247 }
248 continue;
249 }
250#endif
251
252 if (set_nonblocking(client_fd) < 0) {
253 LILA_WARN(Emitter::SERVER, "Failed to set non-blocking on client fd " + std::to_string(client_fd));
254 }
255
256 handle_client(client_fd);
257 }
258}
#define LILA_WARN(emitter, msg)
#define LILA_ERROR(emitter, msg)
std::atomic< bool > m_running
Server running state.
Definition Server.hpp:164
void handle_client(int client_fd)
Handles communication with a single client.
Definition Server.cpp:260
int m_server_fd
Server socket file descriptor.
Definition Server.hpp:163
static int set_nonblocking(int fd)
Definition Server.cpp:62
static std::string socket_error_string(int code)
Definition Server.cpp:33
static int socket_errno()
Definition Server.cpp:24

References LILA_ERROR, LILA_WARN, Lila::set_nonblocking(), Lila::socket_errno(), Lila::socket_error_string(), and Lila::ServerThread::StopToken::stop_requested().

Referenced by start().

+ Here is the call graph for this function:
+ Here is the caller graph for this function: