AGXDynamics  2.31.1.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
WebSocket.h
Go to the documentation of this file.
1 /*
2 Copyright 2007-2021. 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 
18 #ifndef AGXNET_WEBSOCKETS_H
19 #define AGXNET_WEBSOCKETS_H
20 
22 #include <agx/config.h>
23 
24 #if AGX_USE_WEBSOCKETS()
25 
26 #include <agx/Callback.h>
27 #include <agx/HashTable.h>
28 #include <agx/Referenced.h>
29 #include <agxData/Frame.h>
30 #include <agxData/BinaryData.h>
31 #include <agxNet/FramePacket.h>
32 #include <agxNet/PortRange.h>
33 #include <external/json/value.h>
34 #include <queue>
35 
36 
37 
38 // Forward declarations of libwebsockets stuff so we can pass around opaque pointers.
39 struct lws_context;
40 struct lws_protocols;
41 struct lws;
42 
43 
44 namespace agxNet
45 {
46  class WebSocketServer;
49 
55  {
56  public:
57 
60  AGX_DECLARE_POINTER_TYPES(ControlChannel);
61 
62 
63 
71 
72 
76  void setReceiveCallback(ReceiveCallback callback);
77 
78 
82  void send(const agx::String& message);
83  void send(Packet* packet);
84  void send(const StructuredMessage *message);
85 
86 
87 
88  // For libwebsockets only.
89  void messageReceived(void* message, size_t size);
90 
91  void setAnonymous(bool flag);
92  bool isAnonymous() const;
93 
94  bool isAuthenticated() const;
95  void setAuthenticated(bool flag);
96 
97  protected:
98  virtual ~WebSocket();
99 
100  private:
101  friend class WebSocketServer;
102 
106  WebSocket(WebSocketServer* context, lws* socket);
107 
108  private:
109  WebSocketServer* m_context;
110  lws* m_wsiHandle;
111  ReceiveCallback m_receiveCallback;
112  agx::UInt32 m_nextMessageId;
113  bool m_anonymous;
114  bool m_authenticated;
115 
116  struct PacketTransfer
117  {
118  PacketTransfer(Packet *p) : packet(p), numWritten(0) {}
119  PacketTransfer() : packet(nullptr), numWritten(0) {}
120 
121  PacketRef packet;
122  size_t numWritten;
123  };
124 
125  typedef std::queue<PacketTransfer> PacketQueue;
126  PacketQueue m_sendQueue;
127  };
128 
129 
133  class AGXCORE_EXPORT WebSocket::Packet : public agx::Referenced
134  {
135  public:
137  {
139  CONTENT_TEXT
140  };
141 
142  Packet(size_t size, ContentType type);
143 
144  // Convenience method to create a text packet
145  Packet(const agx::String& message);
146  Packet(const agxJson::Value& message);
147 
148  // Convenience method to create a data frame packet
149  Packet(const agxData::Frame *frame);
150 
151 
156  agx::UInt8* getPayload();
157 
158 
159  /*
160  * Returns the size of the payload memory area, in bytes.
161  */
162  size_t getSize() const;
163 
164 
165  ContentType getContentType() const;
166 
167 
168 
169 
170  // Internal
171  int getLibwebsocketsWriteProtocol() const;
172 
173  private:
174  friend class WebSocket;
175  void init(size_t size, ContentType type);
176 
177  protected:
178  virtual ~Packet();
179 
180  private:
181  ContentType m_type;
182 
183  // We use agx::UInt8* because of weaker pointer aliasing rules.
184  agx::UInt8* m_buffer; // Includes both metadata and the payload itself.
185  agx::UInt8* m_message; // Pointer into the m_buffer memory segment, at the start of the payload.
186  size_t m_messageSize;
187  };
188 
189 
195  {
196  public:
197 
203 
204 
205  WebSocketServer(agx::UInt16 port, SocketCallback connectedCallback = SocketCallback(), SocketCallback disconnectedCallback = SocketCallback(), const agx::String& protocol = "agx_stream");
206  WebSocketServer(agxNet::PortRange *range, SocketCallback connectedCallback = SocketCallback(), SocketCallback disconnectedCallback = SocketCallback(), const agx::String& protocol = "agx_stream");
207 
208 
215  bool service(agx::Real timeoutMs = 0);
216 
220  agx::UInt16 getPort() const;
221 
225  bool useSSL() const;
226 
227 
228  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);
229 
230  void send(WebSocket::Packet* packet);
231  void send(const StructuredMessage* message);
232 
233  /*
234  * The following is for libwebsockets only. Should not be called by users.
235  */
236 
237  static WebSocketServer* getServer(lws_context* contextHandle);
238  WebSocket *acceptNewClient(lws* clientHandle);
239  WebSocket* getWebSocket(lws* clientHandle);
240  void connectionClosed(lws* clientHandle);
241  void connectionDestroyed(lws* clientHandle);
242 
243  class SocketEventHandler;
244 
245  public:
247  const SocketTable& getClientSockets();
248 
249  protected:
250  virtual ~WebSocketServer();
251  void initProtocols(const char *protocolName);
252  void init(agx::UInt16 port);
253 
254  private:
255  friend class WebSocket;
256  agx::UInt16 m_port;
257  bool m_runningService;
258  bool m_hasNewSocketEvent;
259 
260  lws_context* m_contextHandle;
261  SocketCallback m_connectedCallback;
262  SocketCallback m_disconnectedCallback;
263 
264  SocketTable m_sockets;
265 
267  static ContextTable s_contexts;
268  lws *m_currentCreatedConnection;
269  agx::String m_protocolName;
270  lws_protocols *m_protocols;
271  bool m_useSSL;
272  };
273 
274 
278  class AGXCORE_EXPORT WebSocket::ControlChannel : public agx::Referenced
279  {
280  public:
282 
285 
286  public:
287  ControlChannel(agx::UInt16 port, const agx::String& token = "");
288  ControlChannel(agxNet::PortRange* portRange, const agx::String& token = "");
289 
290  agx::UInt16 getPort() const;
291 
292  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);
293  void send(const StructuredMessage *message);
294 
295  bool service(agx::Real timeoutMs = 0);
296 
298 
299  void registerMessageHandler(const agx::String& uri, MessageHandler callback);
300 
301  protected:
302  virtual ~ControlChannel();
303 
304  private:
305  void clientConnected(agxNet::WebSocket* client);
306  void clientDisconnected(agxNet::WebSocket* client);
307  void messageReceived(agxNet::WebSocket *socket, agx::UInt8* payload, size_t size);
308 
309  private:
310  agxNet::WebSocketServerRef m_serverSocket;
311  agxNet::WebSocketRefVector m_clientSockets;
312 
314  MessageHandlerTable m_messageHandlerTable;
315  agx::String m_token;
316  agxNet::StructuredMessageRef m_currentMessage;
317  agxNet::WebSocket *m_currentMessageSocket;
318  };
319 
321  AGX_FORCE_INLINE agx::UInt8* WebSocket::Packet::getPayload() { return m_message; }
322  AGX_FORCE_INLINE size_t WebSocket::Packet::getSize() const { return m_messageSize; }
323  AGX_FORCE_INLINE WebSocket::Packet::ContentType WebSocket::Packet::getContentType() const { return m_type; }
324 
325 
327 
328 }
329 
330 // AGX_USE_WEBSOCKETS
331 #endif
332 
333 // Include guard.
334 #endif
void AGXPHYSICS_EXPORT init()
Initialize agx.
A socket that connects to a client.
Definition: WebSocket.h:54
uint8_t UInt8
Definition: Integer.h:38
agx::ref_ptr< Packet > PacketRef
Definition: Packet.h:28
SocketEvent socketDisconnectEvent
Definition: WebSocket.h:284
#define AGX_DECLARE_POINTER_TYPES(type)
Definition: Referenced.h:248
#define AGX_FORCE_INLINE
Definition: Object.h:62
agx::Callback1< WebSocket * > SocketCallback
A callback function that is called whenever a new client connects.
Definition: WebSocket.h:202
agx::Callback3< WebSocket *, agx::UInt8 *, size_t > ReceiveCallback
A callback function that is run when a message is received from the socket.
Definition: WebSocket.h:70
Base class providing referencing counted objects.
Definition: Referenced.h:113
agx::Event2< ControlChannel *, agxNet::WebSocket * > SocketEvent
Definition: WebSocket.h:281
agx::HashTable< lws *, WebSocketRef > SocketTable
Definition: WebSocket.h:243
GLenum GLuint GLenum GLsizei const GLchar * message
Definition: gl.h:5539
AGX_DECLARE_VECTOR_TYPES(Socket)
Handles testing of ports in a range.
Definition: PortRange.h:30
agx::UInt16 getPort() const
Definition: WebSocket.h:326
SocketEvent socketConnectEvent
Definition: WebSocket.h:283
uint16_t UInt16
Definition: Integer.h:39
double Real
Definition: Real.h:42
agx::Callback3< ControlChannel *, agxNet::WebSocket *, agxNet::StructuredMessage * > MessageHandler
Definition: WebSocket.h:297
Inheritance with partial specialization due to bug with ref_ptr containers.
uint32_t UInt32
Definition: Integer.h:40
#define AGXCORE_EXPORT
GLenum type
Definition: gl.h:5539
Packet(size_t size, ContentType type)