1 #pragma once
2 #include <boost/logic/tribool.hpp>
3 #include <string>
4 #include "WebsocketHandler.h"
5 
6 #ifdef WIN32
7 #define size_t_t __int64
8 #else
9 #define size_t_t long long
10 #endif
11 
12 namespace http {
13 	namespace server {
14 
15 		enum opcodes {
16 			opcode_continuation = 0x00,
17 			opcode_text = 0x01,
18 			opcode_binary = 0x02,
19 			opcode_close = 0x08,
20 			opcode_ping = 0x09,
21 			opcode_pong = 0x0a
22 		};
23 
24 		class connection;
25 		class cWebem;
26 
27 		class CWebsocketFrame {
28 		public:
29 			CWebsocketFrame();
30 			~CWebsocketFrame();
31 			bool Parse(const uint8_t *bytes, size_t size);
32 			std::string Payload();
33 			bool isFinal();
34 			size_t Consumed();
35 			opcodes Opcode();
36 			static std::string Create(opcodes opcode, const std::string &payload, bool domasking);
37 		private:
38 			static std::string unmask(const uint8_t *mask, const uint8_t *bytes, size_t payloadlen);
39 			bool fin;
40 			bool rsvi1;
41 			bool rsvi2;
42 			bool rsvi3;
43 			opcodes opcode;
44 			bool masking;
45 			size_t payloadlen, bytes_consumed;
46 			std::string payload;
47 		};
48 
49 		class CWebsocket {
50 		public:
51 			CWebsocket(boost::function<void(const std::string &packet_data)> _MyWrite, cWebem *_webEm, boost::function<void(const std::string &packet_data)> _WSWrite);
52 			~CWebsocket();
53 			virtual boost::tribool parse(const uint8_t *begin, size_t size, size_t &bytes_consumed, bool &keep_alive);
54 			virtual void SendClose(const std::string &packet_data);
55 			virtual void SendPing();
56 			virtual void Start();
57 			virtual void Stop();
58 			virtual CWebsocketHandler *GetHandler();
59 		private:
60 			virtual void OnReceiveText(const std::string &packet_data);
61 			virtual void OnReceiveBinary(const std::string &packet_data);
62 			virtual void OnPong(const std::string &packet_data);
63 			virtual void SendPong(const std::string &packet_data);
64 			std::string packet_data;
65 			bool start_new_packet;
66 			opcodes last_opcode;
67 			std::string OUR_PING_ID;
68 			CWebsocketHandler handler;
69 			boost::function<void(const std::string &packet_data)> MyWrite;
70 		};
71 
72 	}
73 }
74