WebSocket.h 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #pragma once
  2. #include <Critical.h>
  3. #include <functional>
  4. #include <Random.h>
  5. #include <Thread.h>
  6. #include "Client.h"
  7. namespace Network
  8. {
  9. namespace WebSocket
  10. {
  11. struct Frame
  12. {
  13. bool fin, rsv1, rsv2, rsv3; // bit 0 to 3
  14. char opcode; // bit 4 to 7
  15. bool mask; // bit 8
  16. __int64 dataLength; // bit 9 to 15 or to 31 or to 79
  17. unsigned char key[4]; // if mask = 1 then the next 32 bits
  18. char* data; // the data
  19. // combines frames that belong to a message
  20. __declspec(dllexport) Frame& operator+=(const Frame& b);
  21. };
  22. enum DataType
  23. {
  24. TEXT,
  25. BINARY
  26. };
  27. class WebSocketClient : public Framework::Thread
  28. {
  29. private:
  30. std::function<void(
  31. WebSocketClient*, __int64 size, const char* data, DataType typ)>
  32. callback;
  33. Client* client;
  34. Framework::Text path;
  35. Framework::Text host;
  36. Frame* lastPingFrame;
  37. Array<Frame>* queue;
  38. unsigned short port;
  39. Critical c;
  40. Critical c2;
  41. RandomGenerator gen;
  42. bool nextClose;
  43. public:
  44. // Creates a new WebSocket
  45. // path: The path to the resource
  46. // host: The address of the server
  47. // port: The port of the server
  48. __declspec(dllexport) WebSocketClient(
  49. const char* path, const char* host, unsigned short port);
  50. __declspec(dllexport) virtual ~WebSocketClient();
  51. // Sets the function to be called for processing server messages
  52. __declspec(dllexport) void setMessageCallback(
  53. std::function<void(WebSocketClient*,
  54. __int64 size,
  55. const char* data,
  56. DataType typ)> callback);
  57. // Performs the WebSocket handshake if not yet connected
  58. __declspec(dllexport) bool connect();
  59. // Sends a message to the server
  60. // size: The length of the message
  61. // data: The data
  62. // typ: The type of the message
  63. __declspec(dllexport) bool send(
  64. __int64 size, const char* data, DataType typ = TEXT);
  65. // This function processes server messages. It should not be called manually as it is started automatically
  66. __declspec(dllexport) void thread() override;
  67. // aborts the connection
  68. __declspec(dllexport) void disconnect();
  69. // Returns 1 if a connection to the server exists, 0 otherwise
  70. __declspec(dllexport) bool isConnected() const;
  71. };
  72. } // namespace WebSocket
  73. } // namespace Network