Menu

[94f52a]: / poll / socket_server.hpp  Maximize  Restore  History

Download this file

48 lines (38 with data), 1.4 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
#ifndef CHILON_POLL_SOCKET_SERVER_HPP
#define CHILON_POLL_SOCKET_SERVER_HPP
#include <chilon/poll/socket_client.hpp>
#include <exception>
namespace chilon { namespace poll {
struct could_not_bind_socket : std::exception {};
struct could_not_listen : std::exception {};
// Server contract:
// void operator()(int socket)
template <class Server>
struct socket_server : public socket_client< socket_server<Server> > {
typedef socket_client< socket_server<Server> > base_t;
void tcp_listen(int const port, int const nListeners) {
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = INADDR_ANY;
if (-1 == bind(base_t::fd_, (struct sockaddr *)&sin, sizeof(sin)))
throw could_not_bind_socket();
if (-1 == listen(base_t::fd_, nListeners))
throw could_not_listen();
}
virtual void operator()(poll_status const) {
// sockaddr addr;
// socklen_t len;
// int newSocket = ::accept(base_t::fd, &addr, &len);
int newSocket = ::accept(base_t::fd_, 0, 0);
if (newSocket == -1) static_cast<Server &>(*this).error();
else {
fcntl(newSocket, F_SETFL, O_NONBLOCK);
static_cast<Server &>(*this).add_client(newSocket);
}
}
socket_server() {}
socket_server(int socket) : base_t(socket) {}
};
} }
#endif
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.