]> git.sesse.net Git - cubemap/blob - server.h
Implement epoll main loop in Server, and parse header.
[cubemap] / server.h
1 #ifndef _SERVER_H
2 #define _SERVER_H 1
3
4 #include <stdint.h>
5 #include <pthread.h>
6 #include <string>
7 #include <map>
8
9 #define NUM_SERVERS 4
10 #define BACKLOG_SIZE 1048576
11 #define EPOLL_MAX_EVENTS 8192
12 #define EPOLL_TIMEOUT_MS 20
13 #define MAX_CLIENT_REQUEST 16384
14
15 struct Client {
16         // The file descriptor associated with this socket.
17         int sock;
18
19         enum State { READING_REQUEST, SENDING_HEADER, SENDING_DATA };
20         State state;
21
22         // The HTTP request, as sent by the client. If we are in READING_REQUEST,
23         // this might not be finished.
24         std::string client_request;
25
26 #if 0
27         // What stream we're connecting to; parsed from client_request.
28         // Not relevant for READING_REQUEST.
29         string stream_id;
30 #endif
31
32         // Number of bytes we've sent of the header. Only relevant for SENDING_HEADER.
33         size_t header_bytes_sent;
34
35         // Number of bytes we've sent of data. Only relevant for SENDING_DATA.
36         size_t bytes_sent;
37 };
38
39 struct Stream {
40         // The HTTP response header, plus the video stream header (if any).
41         std::string header;
42
43         // The stream data itself, stored in a circular buffer.
44         char data[BACKLOG_SIZE];
45
46         // How many bytes <data> contains. Can very well be larger than BACKLOG_SIZE,
47         // since the buffer wraps.
48         size_t data_size;
49 };
50
51 class Server {
52 public:
53         Server();
54
55         // Start a new thread that handles clients.
56         void run();
57         void add_client(int sock);
58         void add_stream(const std::string &stream_id);
59         void set_header(const std::string &stream_id, const std::string &header);
60         void add_data(const std::string &stream_id, const char *data, size_t bytes);
61
62 private:
63         void process_client(Client *client);
64         void close_client(Client *client);
65
66         pthread_mutex_t mutex;
67
68         // Map from stream ID to stream.
69         std::map<std::string, Stream> streams;
70
71         // Map from file descriptor to client.
72         std::map<int, Client> clients;
73
74         // Used for epoll implementation (obviously).
75         int epoll_fd;
76         epoll_event events[EPOLL_MAX_EVENTS];
77
78         // Recover the this pointer, and call do_work().
79         static void *do_work_thunk(void *arg);
80
81         // The actual worker thread.
82         void do_work();
83 };
84
85 #endif  // !defined(_SERVER_H)