AGX Dynamics 2.40.1.2
Loading...
Searching...
No Matches
Socket.h
Go to the documentation of this file.
1/*
2Copyright 2007-2025. Algoryx Simulation AB.
3
4All AGX source code, intellectual property, documentation, sample code,
5tutorials, scene files and technical white papers, are copyrighted, proprietary
6and confidential material of Algoryx Simulation AB. You may not download, read,
7store, distribute, publish, copy or otherwise disseminate, use or expose this
8material unless having a written signed agreement with Algoryx Simulation AB, or having been
9advised so by Algoryx Simulation AB for a time limited evaluation, or having purchased a
10valid commercial license from Algoryx Simulation AB.
11
12Algoryx Simulation AB disclaims all responsibilities for loss or damage caused
13from using this software, unless otherwise stated in written agreements with
14Algoryx Simulation AB.
15*/
16
17/* The MIT License:
18
19Copyright (c) 2008 Ivan Gagis
20
21Permission is hereby granted, free of charge, to any person obtaining a copy
22of this software and associated documentation files (the "Software"), to deal
23in the Software without restriction, including without limitation the rights
24to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
25copies of the Software, and to permit persons to whom the Software is
26furnished to do so, subject to the following conditions:
27
28The above copyright notice and this permission notice shall be included in
29all copies or substantial portions of the Software.
30
31THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
32IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
33FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
34AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
35LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
36OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
37THE SOFTWARE. */
38
39// (c) Ivan Gagis 2008
40// e-mail: igagis\gmail.com
41
42// Description:
43// cross platform C++ Sockets wrapper
44//
45
46
47#pragma once
48
49#ifdef _MSC_VER
50# pragma warning( disable : 4290)
51# pragma warning( disable: 4275 ) // warning C4275: non dll-interface class
52#endif
53
54
55#include <exception>
56#include <stdexcept>
57#include <new>
58#include <agxNet/FramePacket.h>
59#include <agx/stdint.h>
60#include <agx/agxCore_export.h>
61#include <agx/Singleton.h>
62#include <agx/Referenced.h>
63#include <agx/Vector.h>
64#include <agx/String.h>
65#include <iosfwd>
66
67namespace agxNet{
68
69 //forward declarations
70 class SocketSet;
71 class IPAddress;
72 class Socket;
73
78 class AGXCORE_EXPORT NetError : public std::runtime_error {
79 public:
84 NetError(const char* message) : std::runtime_error(message), m_socket(nullptr) {}
85 NetError(Socket *socket) : std::runtime_error("Connection closed"), m_socket(socket) {}
86 NetError(const char* message, Socket* socket) : std::runtime_error(message), m_socket(socket) {}
87
88 virtual ~NetError() throw() {}
89
90 Socket *getSocket() { return m_socket; }
91 private:
92 Socket *m_socket;
93 };
94
99 public:
104 TimeoutConnectError(const char* message) : NetError(message) {}
105 virtual ~TimeoutConnectError() noexcept {}
106 };
107
112
117 {
118 public:
119
122
129 m_host(h),
130 m_port(p)
131 {}
132
146 m_host(agx::UInt32(h1) + (agx::UInt32(h2)<<8) + (agx::UInt32(h3)<<16) + (agx::UInt32(h4)<<24)),
147 m_port(p)
148 {
149 }
150
157
164 inline bool operator==(const IPAddress& ip){
165 return (this->m_host == ip.m_host) && (this->m_port == ip.m_port);
166 }
167
169 const agx::UInt32& host() const { return m_host; }
170
172 agx::UInt32& host() { return m_host; }
173
175 const agx::UInt16& port() const { return m_port; }
176
178 agx::UInt16& port() { return m_port; }
179
181 private:
182 //parse IP address from string
183 static agx::UInt32 parseString(const char* ip);
184
185 agx::UInt32 m_host;
186 agx::UInt16 m_port;
187
188 };
189
190 std::ostream& operator<<(std::ostream& stream, const IPAddress& adr);
191
201
202 public:
204
208 static Library *instance();
209
214 virtual void shutdown() override;
215
223 IPAddress getHostByName(const char *hostName, agx::UInt16 port);
224
225 SINGLETON_CLASSNAME_METHOD();
226
227 private:
228
229 virtual ~Library();
230
231 void initSockets();
232 void deinitSockets();
233
234 static Library *s_instance;
235 bool m_initialized;
236 };
237
245 friend class SocketSet;
246
247 public:
248 //this type will hold system specific socket handle.
249 //this buffer should be large enough to hold socket handle in different systems.
250 //sizeof(u64) looks enough so far (need to work on 64-bit platforms too).
251#ifndef DOC_DONT_EXTRACT //direction to doxygen not to extract this class
253 agx::UInt8 buffer[sizeof(uint64_t)];
254 };
255#endif//~DOC_DONT_EXTRACT
256
257 public:
258
264 bool isValid()const;
265
266 void setBlocking(bool flag);
267 bool isBlocking() const { return m_blocking; }
268
277 inline bool isReady()const
278 {
279 return m_readyToReceive;
280 }
281
282 void select(agx::UInt32 timeoutMillis = 0);
283
284 inline bool readyToReceive() const
285 {
286 return m_readyToReceive;
287 }
288
289 inline bool readyToSend() const
290 {
291 return m_readyToSend;
292 }
293
294 inline const IPAddress& adr() const { return m_adr; }
295
299 void close();
300
311 static int getLastError();
312
313 protected:
314
316 virtual ~Socket(){
317 this->close();
318 }
319
320 Socket(const IPAddress& adr = IPAddress());
321
323
324 protected:
325 // bool m_isReady;
330
332 };
333
334
341 friend class TCPServerSocket;
342 public:
347
355 //copy constructor
356 TCPSocket(const TCPSocket& s, const IPAddress& adr = IPAddress()) : Socket(adr) {
357 //NOTE: that operator= calls destructor, so this->socket should be invalid, base class constructor takes care about it.
358 this->operator=(s);//same as auto_ptr
359 }
360
368 TCPSocket(const IPAddress& ip, bool disableNaggle = false) : Socket(ip) {
369 this->open(ip, disableNaggle);
370 }
371
379 this->Socket::operator=(s);
380 return *this;
381 }
382
389 void open(const IPAddress& ip, bool disableNaggle = false);
390
399
409 //returns 0 if connection was closed by peer
410 size_t recv(agx::UInt8* buf, size_t maxSize);
411
412 void sendBlocking(const agx::UInt8 *data, agx::UInt32 size);
414
415 void sendBlocking(const StructuredMessage *message);
416
417 private:
418 void disableNaggle();
419 };
420
421
422
430 public:
434 TCPServerSocket() : m_disableNaggle(false) {}
435
443 //copy constructor
444 TCPServerSocket(const TCPServerSocket& s) : Socket(), m_disableNaggle(s.m_disableNaggle)
445 {
446 //NOTE: that operator= calls destructor, so this->socket should be invalid, base class constructor takes care about it.
447 this->operator=(s);//same as auto_ptr
448 }
449
457 this->Socket::operator=(s);
458 return *this;
459 }
460
468 TCPServerSocket(agx::UInt16 port, bool disableNaggle = false){
469 this->open(port, disableNaggle);
470 }
471
478 void open(agx::UInt16 port, bool disableNaggle = false);
479
490 private:
491 bool m_disableNaggle;//this flag indicates if accepted sockets should be created with disabled Naggle
492
493 };
494
497 public:
499
510 void open(agx::UInt16 port);
511
512
513 inline void open(){
514 this->open(0);
515 }
516
517 //returns number of bytes sent, should be less or equal to size.
518 size_t send(const agx::UInt8* buf, agx::UInt16 size, IPAddress destinationIP);
519
520 //returns number of bytes received, 0 if connection was gracefully closed (???).
521 agx::UInt32 recv(agx::UInt8* buf, agx::UInt16 maxSize, IPAddress &out_SenderIP);
522
523 protected:
524 virtual ~UDPSocket(){
525 this->close();
526 }
527 };
528
529
540
541 public:
542
548
553 inline size_t getNumSockets()const{return m_set.size(); }
554
559 size_t getMaxSockets()const;
560
566 bool addSocket(Socket *sock);
567
573 bool removeSocket(Socket *sock);
574
585 //This function checks to see if data is available for reading on the
586 //given set of sockets. If 'timeout' is 0, it performs a quick poll,
587 //otherwise the function returns when either data is available for
588 //reading, or the timeout in milliseconds has elapsed, which ever occurs
589 //first. This function returns true if there are any sockets ready for reading,
590 //or false if there was an error with the select() system call.
591 bool checkSockets(agx::UInt32 timeoutMillis);
592
593 const SocketRefVector& getSockets() const { return m_set; }
594
595 protected:
596
601 virtual ~SocketSet(){
602 m_set.clear();
603 }
604
605 private:
606
607 SocketRefVector m_set;
608
609 };
610}
#define AGX_DECLARE_POINTER_TYPES(type)
Definition: Referenced.h:254
#define AGXCORE_EXPORT
#define AGX_DECLARE_VECTOR_TYPES(type)
Definition: agx/Vector.h:34
a structure which holds IP address
Definition: Socket.h:117
agx::UInt32 & host()
Definition: Socket.h:172
const agx::UInt32 & host() const
Definition: Socket.h:169
IPAddress()
Default constructor.
agx::String string() const
IPAddress(agx::UInt32 h, agx::UInt16 p)
Create IP address specifying exact ip address and port number.
Definition: Socket.h:128
const agx::UInt16 & port() const
Definition: Socket.h:175
IPAddress(const agx::String &ip, agx::UInt16 p)
Create IP address specifying ip address as string and port number.
bool operator==(const IPAddress &ip)
compares two IP addresses for equality.
Definition: Socket.h:164
IPAddress(agx::UInt8 h1, agx::UInt8 h2, agx::UInt8 h3, agx::UInt8 h4, agx::UInt16 p)
Create IP address specifying exact ip address as 4 bytes and port number.
Definition: Socket.h:145
agx::UInt16 & port()
Definition: Socket.h:178
Library singleton class.
Definition: Socket.h:200
static Library * instance()
Get the singleton instance.
virtual void shutdown() override
instance the object, after this, the object cannot be used anymore.
IPAddress getHostByName(const char *hostName, agx::UInt16 port)
Resolve host IP by its name.
Basic exception class.
Definition: Socket.h:78
NetError(const char *message)
Exception constructor.
Definition: Socket.h:84
NetError(Socket *socket)
Definition: Socket.h:85
Socket * getSocket()
Definition: Socket.h:90
virtual ~NetError()
Definition: Socket.h:88
NetError(const char *message, Socket *socket)
Definition: Socket.h:86
size_t getMaxSockets() const
Returns maximal number of sockets the system allows.
bool addSocket(Socket *sock)
Add a socket to socket set.
SocketSet()
Creates a socket set of the specified size.
virtual ~SocketSet()
Destroys the socket set.
Definition: Socket.h:601
size_t getNumSockets() const
Returns number of sockets the socket set currently holds.
Definition: Socket.h:553
bool checkSockets(agx::UInt32 timeoutMillis)
Check sockets from socket set for activity.
const SocketRefVector & getSockets() const
Definition: Socket.h:593
bool removeSocket(Socket *sock)
Remove socket from socket set.
bool m_blocking
Definition: Socket.h:328
void select(agx::UInt32 timeoutMillis=0)
static int getLastError()
Returns the last reported error from a system call.
void close()
Closes the socket disconnecting it if necessary.
bool isValid() const
Tells whether the socket is opened or not.
bool readyToReceive() const
Definition: Socket.h:284
bool m_readyToReceive
Definition: Socket.h:326
Socket & operator=(const Socket &s)
virtual ~Socket()
Destructor.
Definition: Socket.h:316
SystemIndependentSocketHandle m_socket
Definition: Socket.h:331
IPAddress m_adr
Definition: Socket.h:329
const IPAddress & adr() const
Definition: Socket.h:294
void setBlocking(bool flag)
bool isBlocking() const
Definition: Socket.h:267
bool m_readyToSend
Definition: Socket.h:327
bool readyToSend() const
Definition: Socket.h:289
bool isReady() const
Tells whether there is some activity on the socket or not.
Definition: Socket.h:277
Socket(const IPAddress &adr=IPAddress())
TCPServerSocket & operator=(const TCPServerSocket &s)
Assignment operator, works similar to std::auto_ptr::operator=().
Definition: Socket.h:456
TCPServerSocket(const TCPServerSocket &s)
A copy constructor.
Definition: Socket.h:444
TCPSocket * accept()
Accepts one of the pending connections, non-blocking.
TCPServerSocket(agx::UInt16 port, bool disableNaggle=false)
A constructor which automatically calls TCPServerSocket::Open() method.
Definition: Socket.h:468
TCPServerSocket()
Creates an invalid (unopened) TCP server socket.
Definition: Socket.h:434
void open(agx::UInt16 port, bool disableNaggle=false)
Connects the socket or starts listening on it.
void sendBlocking(const agx::UInt8 *data, agx::UInt32 size)
void open(const IPAddress &ip, bool disableNaggle=false)
Connects the socket.
TCPSocket(const IPAddress &ip, bool disableNaggle=false)
A constructor which automatically calls TCPSocket::Open() method.
Definition: Socket.h:368
size_t recv(agx::UInt8 *buf, size_t maxSize)
Receive data from connected socket.
TCPSocket(const TCPSocket &s, const IPAddress &adr=IPAddress())
A copy constructor.
Definition: Socket.h:356
void recvBlocking(agx::UInt8 *buf, agx::UInt32 size)
TCPSocket()
Constructs an invalid TCP socket object.
Definition: Socket.h:346
TCPSocket & operator=(const TCPSocket &s)
Assignment operator, works similar to std::auto_ptr::operator=().
Definition: Socket.h:378
void sendBlocking(const StructuredMessage *message)
agx::UInt32 send(const agx::UInt8 *data, agx::UInt32 size)
Send data to connected socket.
Indicates a timeout between server/client.
Definition: Socket.h:98
TimeoutConnectError(const char *message)
Exception constructor.
Definition: Socket.h:104
virtual ~TimeoutConnectError() noexcept
Definition: Socket.h:105
size_t send(const agx::UInt8 *buf, agx::UInt16 size, IPAddress destinationIP)
virtual ~UDPSocket()
Definition: Socket.h:524
void open(agx::UInt16 port)
Open the socket.
agx::UInt32 recv(agx::UInt8 *buf, agx::UInt16 maxSize, IPAddress &out_SenderIP)
Base class providing referencing counted objects.
Definition: Referenced.h:120
Base class for Singletons that should have its shutdown called explicitly before exit of the applicat...
Definition: Singleton.h:31
Containins classes for sending/reading data over sockets as well as compression functionality.
Definition: MacUtil.h:23
agx::UInt16 AGXCORE_EXPORT getAvailablePort()
std::ostream & operator<<(std::ostream &stream, const IPAddress &adr)
The agx namespace contains the dynamics/math part of the AGX Dynamics API.
uint16_t UInt16
Definition: Integer.h:31
uint32_t UInt32
Definition: Integer.h:32
uint8_t UInt8
Definition: Integer.h:30
STL namespace.