/usr/share/doc/libkyototycoon2/example/ktpollex.cc is in kyototycoon-doc 0.9.56-1build2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | #include <ktsocket.h>
using namespace std;
using namespace kyototycoon;
// the flag whether the server is alive
Poller* g_poll = NULL;
// stop the running server
static void stopserver(int signum) {
if (g_poll) g_poll->abort();
g_poll = NULL;
}
// main routine
int main(int argc, char** argv) {
// set the signal handler to stop the server
setkillsignalhandler(stopserver);
// open the server socket
ServerSocket serv;
serv.open("127.0.0.1:1978");
// open the event notifier
Poller poll;
poll.open();
g_poll = &poll;
// deposit the server socket into the poller
serv.set_event_flags(Pollable::EVINPUT);
poll.deposit(&serv);
// event loop
while (g_poll) {
// wait one or more active requests
if (poll.wait()) {
// iterate all active requests
Pollable* event;
while ((event = poll.next()) != NULL) {
if (event == &serv) {
// accept a new connection
Socket* sock = new Socket;
sock->set_timeout(1.0);
if (serv.accept(sock)) {
sock->set_event_flags(Pollable::EVINPUT);
poll.deposit(sock);
}
// undo the server socket
serv.set_event_flags(Pollable::EVINPUT);
poll.undo(&serv);
} else {
// process each request
Socket* sock = (Socket*)event;
// read a line from the client socket
char line[1024];
if (sock->receive_line(line, sizeof(line))) {
if (!kc::stricmp(line, "/quit")) {
// process the quit command
sock->printf("> Bye!\n");
poll.withdraw(sock);
sock->close();
delete sock;
} else {
// echo back the message
sock->printf("> %s\n", line);
// undo the client socket
serv.set_event_flags(Pollable::EVINPUT);
poll.undo(sock);
}
} else {
// process a connection closed by the client
poll.withdraw(sock);
sock->close();
delete sock;
}
}
}
}
}
// clean up all connections
if (poll.flush()) {
Pollable* event;
while ((event = poll.next()) != NULL) {
if (event != &serv) {
Socket* sock = (Socket*)event;
poll.withdraw(sock);
sock->close();
delete sock;
}
}
}
// close the event notifier
poll.close();
// close the server socket
serv.close();
return 0;
}
|