| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- #pragma once
- #include <Critical.h>
- #include <functional>
- #include <Random.h>
- #include <Thread.h>
- #include "Client.h"
- namespace Network
- {
- namespace WebSocket
- {
- struct Frame
- {
- bool fin, rsv1, rsv2, rsv3; // bit 0 to 3
- char opcode; // bit 4 to 7
- bool mask; // bit 8
- __int64 dataLength; // bit 9 to 15 or to 31 or to 79
- unsigned char key[4]; // if mask = 1 then the next 32 bits
- char* data; // the data
- // combines frames that belong to a message
- __declspec(dllexport) Frame& operator+=(const Frame& b);
- };
- enum DataType
- {
- TEXT,
- BINARY
- };
- class WebSocketClient : public Framework::Thread
- {
- private:
- std::function<void(
- WebSocketClient*, __int64 size, const char* data, DataType typ)>
- callback;
- Client* client;
- Framework::Text path;
- Framework::Text host;
- Frame* lastPingFrame;
- Array<Frame>* queue;
- unsigned short port;
- Critical c;
- Critical c2;
- RandomGenerator gen;
- bool nextClose;
- public:
- // Creates a new WebSocket
- // path: The path to the resource
- // host: The address of the server
- // port: The port of the server
- __declspec(dllexport) WebSocketClient(
- const char* path, const char* host, unsigned short port);
- __declspec(dllexport) virtual ~WebSocketClient();
- // Sets the function to be called for processing server messages
- __declspec(dllexport) void setMessageCallback(
- std::function<void(WebSocketClient*,
- __int64 size,
- const char* data,
- DataType typ)> callback);
- // Performs the WebSocket handshake if not yet connected
- __declspec(dllexport) bool connect();
- // Sends a message to the server
- // size: The length of the message
- // data: The data
- // typ: The type of the message
- __declspec(dllexport) bool send(
- __int64 size, const char* data, DataType typ = TEXT);
- // This function processes server messages. It should not be called manually as it is started automatically
- __declspec(dllexport) void thread() override;
- // aborts the connection
- __declspec(dllexport) void disconnect();
- // Returns 1 if a connection to the server exists, 0 otherwise
- __declspec(dllexport) bool isConnected() const;
- };
- } // namespace WebSocket
- } // namespace Network
|