AGX Dynamics  2.37.3.2
WebSocket.h
Go to the documentation of this file.
1 /*
2 Copyright 2007-2024. Algoryx Simulation AB.
3 
4 All AGX source code, intellectual property, documentation, sample code,
5 tutorials, scene files and technical white papers, are copyrighted, proprietary
6 and confidential material of Algoryx Simulation AB. You may not download, read,
7 store, distribute, publish, copy or otherwise disseminate, use or expose this
8 material unless having a written signed agreement with Algoryx Simulation AB, or having been
9 advised so by Algoryx Simulation AB for a time limited evaluation, or having purchased a
10 valid commercial license from Algoryx Simulation AB.
11 
12 Algoryx Simulation AB disclaims all responsibilities for loss or damage caused
13 from using this software, unless otherwise stated in written agreements with
14 Algoryx Simulation AB.
15  */
16 
17 #pragma once
18 
19 #include <agx/config/AGX_USE_WEBSOCKETS.h>
20 #include <agx/config.h>
21 
22 #if AGX_USE_WEBSOCKETS()
23 
24 #include <agx/Callback.h>
25 #include <agx/HashTable.h>
26 #include <agx/Referenced.h>
27 #include <agxData/Frame.h>
28 #include <agxData/BinaryData.h>
29 #include <agxNet/FramePacket.h>
30 #include <agxNet/PortRange.h>
31 #include <json/value.h>
32 #include <queue>
33 
34 
35 
36 // Forward declarations of libwebsockets stuff so we can pass around opaque pointers.
37 struct lws_context;
38 struct lws_protocols;
39 struct lws;
40 
41 
42 namespace agxNet
43 {
44  class WebSocketServer;
45  AGX_DECLARE_POINTER_TYPES(WebSocket);
46  AGX_DECLARE_VECTOR_TYPES(WebSocket);
47 
52  class AGXCORE_EXPORT WebSocket : public agx::Referenced
53  {
54  public:
55 
58  AGX_DECLARE_POINTER_TYPES(ControlChannel);
59 
60 
61 
69 
70 
74  void setReceiveCallback(ReceiveCallback callback);
75 
76 
80  void send(const agx::String& message);
81  void send(Packet* packet);
82  void send(const StructuredMessage *message);
83 
84 
85  // For recieving partial packages
86  void resetPartialMessage();
87  bool hasPartialMessage();
88  void appendPartialMessage(void* pmsg, size_t size, size_t remaining);
89  void receivePartialMessage();
90 
91 
92  // For libwebsockets only.
93  void messageReceived(void* message, size_t size);
94 
95  void setAnonymous(bool flag);
96  bool isAnonymous() const;
97 
98  bool isAuthenticated() const;
99  void setAuthenticated(bool flag);
100 
101  protected:
102  virtual ~WebSocket();
103 
104  private:
105  friend class WebSocketServer;
106 
110  WebSocket(WebSocketServer* context, lws* socket);
111 
112  private:
113  WebSocketServer* m_context;
114  lws* m_wsiHandle;
115  ReceiveCallback m_receiveCallback;
116  agx::UInt32 m_nextMessageId;
117  bool m_anonymous;
118  bool m_authenticated;
119 
120  // For partial message handling
121  agx::UInt8* m_partialMessage;
122  size_t m_partialMessageCurrOffset;
123 
124  struct PacketTransfer
125  {
126  PacketTransfer(Packet *p) : packet(p), numWritten(0) {}
127  PacketTransfer() : packet(nullptr), numWritten(0) {}
128 
129  PacketRef packet;
130  size_t numWritten;
131  };
132 
133  typedef std::queue<PacketTransfer> PacketQueue;
134  PacketQueue m_sendQueue;
135  };
136 
137 
141  class AGXCORE_EXPORT WebSocket::Packet : public agx::Referenced
142  {
143  public:
144  enum ContentType
145  {
146  CONTENT_BINARY,
147  CONTENT_TEXT
148  };
149 
150  Packet(size_t size, ContentType type);
151 
152  // Convenience method to create a text packet
153  Packet(const agx::String& message);
154  Packet(const agxJson::Value& message);
155 
156  // Convenience method to create a data frame packet
157  Packet(const agxData::Frame *frame);
158 
159 
164  agx::UInt8* getPayload();
165 
166 
167  /*
168  * Returns the size of the payload memory area, in bytes.
169  */
170  size_t getSize() const;
171 
172 
173  ContentType getContentType() const;
174 
175 
176 
177 
178  // Internal
179  int getLibwebsocketsWriteProtocol() const;
180 
181  private:
182  friend class WebSocket;
183  void init(size_t size, ContentType type);
184 
185  protected:
186  virtual ~Packet();
187 
188  private:
189  ContentType m_type;
190 
191  // We use agx::UInt8* because of weaker pointer aliasing rules.
192  agx::UInt8* m_buffer; // Includes both metadata and the payload itself.
193  agx::UInt8* m_message; // Pointer into the m_buffer memory segment, at the start of the payload.
194  size_t m_messageSize;
195  };
196 
197 
201  AGX_DECLARE_POINTER_TYPES(WebSocketServer);
202  class AGXCORE_EXPORT WebSocketServer : public agx::Referenced
203  {
204  public:
205 
210  typedef agx::Callback1<WebSocket*> SocketCallback;
211 
212 
213  WebSocketServer(agx::UInt16 port, SocketCallback connectedCallback = SocketCallback(), SocketCallback disconnectedCallback = SocketCallback(), const agx::String& protocol = "agx_stream");
214  WebSocketServer(agxNet::PortRange *range, SocketCallback connectedCallback = SocketCallback(), SocketCallback disconnectedCallback = SocketCallback(), const agx::String& protocol = "agx_stream");
215 
216 
223  bool service(agx::Real timeoutMs = 0);
224 
228  agx::UInt16 getPort() const;
229 
233  bool useSSL() const;
234 
235 
236  WebSocket *createConnection(const agx::String& address, agx::UInt16 port, bool useSSL = false, const agx::String& path = "/", const agx::String& protocol = "agx_stream", bool isAnonymous = false);
237 
238  void send(WebSocket::Packet* packet);
239  void send(const StructuredMessage* message);
240 
241  /*
242  * The following is for libwebsockets only. Should not be called by users.
243  */
244 
245  static WebSocketServer* getServer(lws_context* contextHandle);
246  WebSocket *acceptNewClient(lws* clientHandle);
247  WebSocket* getWebSocket(lws* clientHandle);
248  void connectionClosed(lws* clientHandle);
249  void connectionDestroyed(lws* clientHandle);
250 
251  class SocketEventHandler;
252 
253  public:
254  typedef agx::HashTable<lws*, WebSocketRef> SocketTable;
255  const SocketTable& getClientSockets();
256 
257  protected:
258  virtual ~WebSocketServer();
259  void initProtocols(const char *protocolName);
260  void init(agx::UInt16 port);
261 
262  private:
263  friend class WebSocket;
264  agx::UInt16 m_port;
265  bool m_runningService;
266  bool m_hasNewSocketEvent;
267 
268  lws_context* m_contextHandle;
269  SocketCallback m_connectedCallback;
270  SocketCallback m_disconnectedCallback;
271 
272  SocketTable m_sockets;
273 
275  static ContextTable s_contexts;
276  lws *m_currentCreatedConnection;
277  agx::String m_protocolName;
278  lws_protocols *m_protocols;
279  bool m_useSSL;
280  };
281 
282 
286  class AGXCORE_EXPORT WebSocket::ControlChannel : public agx::Referenced
287  {
288  public:
290 
291  SocketEvent socketConnectEvent;
292  SocketEvent socketDisconnectEvent;
293 
294  public:
295  ControlChannel(agx::UInt16 port, const agx::String& token = "");
296  ControlChannel(agxNet::PortRange* portRange, const agx::String& token = "");
297 
298  agx::UInt16 getPort() const;
299 
300  agxNet::WebSocket *createConnection(const agx::String& address, agx::UInt16 port, bool useSSL = false, const agx::String& path = "/", const agx::String& protocol = "agx_stream", bool isAnonymous = false);
301  void send(const StructuredMessage *message);
302 
303  bool service(agx::Real timeoutMs = 0);
304 
306 
307  void registerMessageHandler(const agx::String& uri, MessageHandler callback);
308 
309  protected:
310  virtual ~ControlChannel();
311 
312  private:
313  void clientConnected(agxNet::WebSocket* client);
314  void clientDisconnected(agxNet::WebSocket* client);
315  void messageReceived(agxNet::WebSocket *socket, agx::UInt8* payload, size_t size);
316 
317  private:
318  agxNet::WebSocketServerRef m_serverSocket;
319  agxNet::WebSocketRefVector m_clientSockets;
320 
321  typedef agx::HashTable<agx::String, MessageHandler> MessageHandlerTable;
322  MessageHandlerTable m_messageHandlerTable;
323  agx::String m_token;
324  agxNet::StructuredMessageRef m_currentMessage;
325  agxNet::WebSocket *m_currentMessageSocket;
326  };
327 
329  AGX_FORCE_INLINE agx::UInt8* WebSocket::Packet::getPayload() { return m_message; }
330  AGX_FORCE_INLINE size_t WebSocket::Packet::getSize() const { return m_messageSize; }
331  AGX_FORCE_INLINE WebSocket::Packet::ContentType WebSocket::Packet::getContentType() const { return m_type; }
332 
333 
334  AGX_FORCE_INLINE agx::UInt16 WebSocketServer::getPort() const { return m_port; }
335 
336 }
337 
338 // AGX_USE_WEBSOCKETS
339 #endif
340 
Containins classes for sending/reading data over sockets as well as compression functionality.
Definition: MacUtil.h:22
void AGXPHYSICS_EXPORT init()
Initialize AGX Dynamics API including thread resources and must be executed before using the AGX API...
uint8_t UInt8
Definition: Integer.h:38
agx::ref_ptr< Packet > PacketRef
Definition: Packet.h:28
#define AGX_DECLARE_POINTER_TYPES(type)
Definition: Referenced.h:254
#define AGX_FORCE_INLINE
Definition: Object.h:59
Base class providing referencing counted objects.
Definition: Referenced.h:119
Templated callback with one argument.
Definition: Callback.h:100
Templated callback with three arguments.
Definition: Callback.h:181
Smart pointer for handling referenced counted objects.
Definition: ref_ptr.h:29
Handles testing of ports in a range.
Definition: PortRange.h:29
An event with two arguments.
Definition: Event.h:121
uint16_t UInt16
Definition: Integer.h:39
double Real
Definition: Real.h:42
#define AGX_DECLARE_VECTOR_TYPES(type)
Definition: Vector.h:34
Inheritance with partial specialization due to bug with ref_ptr containers.
uint32_t UInt32
Definition: Integer.h:40
#define AGXCORE_EXPORT