blob: a638ea836decfb330285777e23340de6785ebd2d (
plain) (
blame)
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
|
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include <zenhttp/websocket.h>
#include <zencore/thread.h>
ZEN_THIRD_PARTY_INCLUDES_START
#include <asio.hpp>
ZEN_THIRD_PARTY_INCLUDES_END
#include <deque>
#include <memory>
#include <vector>
namespace zen::asio_http {
/**
* WebSocket connection over an ASIO TCP socket
*
* Owns the TCP socket (moved from HttpServerConnection after the 101 handshake)
* and runs an async read/write loop to exchange WebSocket frames.
*
* Lifetime is managed solely through intrusive reference counting (RefCounted).
* The async read/write callbacks capture Ref<WsAsioConnection> to keep the
* connection alive for the duration of the async operation. The service layer
* also holds a Ref<WebSocketConnection>.
*/
class WsAsioConnection : public WebSocketConnection
{
public:
WsAsioConnection(std::unique_ptr<asio::ip::tcp::socket> Socket, IWebSocketHandler& Handler);
~WsAsioConnection() override;
/**
* Start the async read loop. Must be called once after construction
* and the 101 response has been sent.
*/
void Start();
// WebSocketConnection interface
void SendText(std::string_view Text) override;
void SendBinary(std::span<const uint8_t> Data) override;
void Close(uint16_t Code, std::string_view Reason) override;
bool IsOpen() const override;
private:
void EnqueueRead();
void OnDataReceived(const asio::error_code& Ec, std::size_t ByteCount);
void ProcessReceivedData();
void EnqueueWrite(std::vector<uint8_t> Frame);
void FlushWriteQueue();
void OnWriteComplete(const asio::error_code& Ec, std::size_t ByteCount);
void DoClose(uint16_t Code, std::string_view Reason);
std::unique_ptr<asio::ip::tcp::socket> m_Socket;
IWebSocketHandler& m_Handler;
asio::streambuf m_ReadBuffer;
RwLock m_WriteLock;
std::deque<std::vector<uint8_t>> m_WriteQueue;
bool m_IsWriting = false;
std::atomic<bool> m_IsOpen{true};
bool m_CloseSent = false;
};
} // namespace zen::asio_http
|