Polygon Crucher SDK - Documentation
Documentation
Loading...
Searching...
No Matches
XSocket.h
Go to the documentation of this file.
1//! @file XSocket.h
2//! A convenient socket class for sending information over the network
3//!
4//////////////////////////////////////////////////////////////////
5#if !defined(XSOCKET_H)
6#define XSOCKET_H
7
8#ifdef _MSC_VER
9#pragma once
10#endif // _MSC_VER
11
12BEGIN_MOOTOOLS_NAMESPACE
13
14#ifdef __WINDOWS__
15#include <Winsock2.h>
16typedef SOCKET xSocket;
17#elif defined(__APPLE__) || defined(__LINUX__)
18typedef int xSocket;
19#endif
20
21#define XSOCKET_INVALID_HANDLE ((xSocket)(-1))
22#define XSOCKET_INVALID_SIZE ((fileuint)(-1))
23
24class CServerListenThread;
25class CCustomData;
26class CXThread;
27class DLL_TOOLSFUNCTION CXSocket : public CXObject
28{
29 DECLARE_DYNAMIC_XOBJECT(CXSocket)
30
31 friend CServerListenThread;
32
33 public:
34 typedef enum
35 {
36 SOCKET_IDLE_MESSAGE = 0, // Can be used to check if socket still exists on the client side (SendDatas(SOCKET_IDLE_MESSAGE, NULL, 0)). If data provided with this message, it will be ignored by the server socket.
37 } SocketMessageID;
38
39 typedef struct
40 {
41 const void *data;
42 fileuint size;
44
45 typedef enum SocketError XEnumType(unsigned int)
46 {
47 SOCKET_ERROR_NONE = 0,
48 SOCKET_ERROR_NO_SERVICE,
49 SOCKET_ERROR_CANT_GET_HOST_ADDRESS,
50 SOCKET_ERROR_NOT_CREATED, // The socket as not be created
51 SOCKET_ERROR_CANT_CREATE,
52 SOCKET_ERROR_CANT_CLOSE,
53 SOCKET_ERROR_CANT_CONNECT,
54 SOCKET_ERROR_CANT_LISTEN,
55 SOCKET_ERROR_CANT_BIND,
56 SOCKET_ERROR_INIT_FAILS_FIRST = SOCKET_ERROR_NO_SERVICE,
57 SOCKET_ERROR_INIT_FAILS_LAST = SOCKET_ERROR_CANT_BIND,
58 SOCKET_ERROR_CANT_SEND,
59 SOCKET_ERROR_CANT_SELECT,
60 SOCKET_ERROR_CANCEL, // Reception cancel
61 SOCKET_ERROR_NO_DATA_AVAILABLE, // There is no data available when calling ReadData with ONLY_IF_AVAILABLE_DATA or WAIT_FOR_AVAILABLE_DATA
62 SOCKET_ERROR_CONNECTION_CLOSED,
63 SOCKET_ERROR_CANT_RECEIVE,
64 } SocketError;
65
66 typedef enum SocketFlags XEnumType(unsigned int)
67 {
68 SOCKET_FLAGS_NONE = 0x00,
69 SOCKET_FLAGS_CLIENT = 0x01,
70 SOCKET_FLAGS_SERVER = 0x02, // Client and server flags are mutually exclusive
71
72 // Internal flags
73 SOCKET_FLAGS_KEEP_OPEN_ON_DESTROY = 0x10000,
74 } SocketFlags;
75
76 typedef enum ReadDataMode XEnumType(unsigned int)
77 {
78 READ_WAITING_DATA = 0, // We know some waiting data exists
79 ONLY_IF_AVAILABLE_DATA, // If data is available get it, otherwise return immediately
80 WAIT_FOR_AVAILABLE_DATA // Wait until some data is available
81 } ReadDataMode;
82
83 typedef CXArray<DataBlockInfo> CDataBlockArray;
84 typedef bool (*SocketReceiveDataCallback)(CXSocket& clientSocket, unsigned int messageID, const void *memory, fileuint dataSize, const CDataBlockArray& blocks, void *callbackData);
85 typedef bool (*SocketUserCancelCallback)(void *callbackData);
86
87 protected:
88 mutable SocketError errorCode;
89 unsigned int flags;
90 unsigned int maxClient, clientCount; // Max client number for a server socket, and client count
91 xSocket *clientSockets;
92 xSocket socketHandle;
93 CXThread *serverListening;
94 void *callbackUserData;
95 SocketReceiveDataCallback receiveDataCallback;
96 SocketUserCancelCallback userCancelCallback;
97
98 // Init the socket service if needed by the O/S (automatically done)
99 static bool InitService();
100 static void CloseService(); // (automatically done when calling CloseMootoolsApplication), otherwise DIY
101
102 bool SendData(const void *data, fileuint datasize) const; // Return true if all the data has been sent
103 bool ReadDataStream(void *message, void *&data, ReadDataMode mode) const; // Return true if data read correctly, false otherwise. In such case GetErrorCode allow to know what occured (SOCKET_ERROR_CANCEL, SOCKET_ERROR_NO_DATA_AVAILABLE, SOCKET_ERROR_CONNECTION_CLOSE or SOCKET_ERROR_CANT_RECEIVE)
104 static unsigned int GetDataBlocks(void *message, const void *data, CDataBlockArray& blocks);
105
106 public:
107 CXSocket();
108 virtual ~CXSocket();
109
110 // Socket useful methods
111 xSocket GetHandle();
112 const xSocket GetHandle() const;
113 bool Attach(xSocket handle, bool clientSocket, bool closeOnDestroy); // Return false if a socket is already attached
114 bool Attach(const xSocket handle); // Return false if a socket is already attached
115 bool CloseSocket();
116
117 // Callback events
118 void SetCallbackData(void *callbackUserData); // Set the user data use in the callbacks.
119 virtual bool UserCancel() const; // Return true if the data exchange should be cancel. This is used both for client and server, reception and sending.
120 void SetUserCancelCallback(SocketUserCancelCallback callback); // Can be used if you don't want to override CXSocket class. Cf. UserCancel
121
122 virtual bool ReceiveData(CXSocket& clientSocket, unsigned int messageID, const void *memory, fileuint dataSize, const CDataBlockArray& blocks); // Called by an external thread when server receive a message and some data. Return true to confirm that you handle it. memory is a temporary pointer and should not be stored. clientSocket can be used to send a confirmation to the client. It is temporary and should not be stored. Blocks has a least one element. It contains pointer to each data block, if several blocks are sent.
123 void SetReceiveDataCallback(SocketReceiveDataCallback callback); // Can be used if you don't want to override CXSocket class. Cf. ReceiveData
124
125 // Error information
126 SocketError GetErrorCode() const { return errorCode; }
127 void SetErrorCode(CXSocket::SocketError error) { errorCode = error; }
128
129 // Read / write data
130 bool SendCustomData(unsigned int messageID, const CCustomData& data) const;
131 bool SendDatas(unsigned int messageID, const void *data, fileuint size, ...) const; // Send multiple datas block in a single message. At reception, each data block is preceed by a fileuint which inform about the size block of the following memory. ReceiveData contains the description of each blocks. Sum of the this fileuint is egal to total ReceiveData dataSize
132
133 bool ReadCustomData(unsigned int& messageID, CCustomData& data, ReadDataMode mode = ONLY_IF_AVAILABLE_DATA) const; // Return true if some data has been read. false otherwise, which means that an error might occured (socket connection fails...)
134 void *ReadDatas(unsigned int & messageID, fileuint & datasize, CDataBlockArray& blocks, ReadDataMode mode) const; // Retrieve information that has been sent with SendDatas. Return the global memory blocks and its datasize. Return also block array, that contains the pointer of the data memory for each block. Uses Free to delete the return memory.
135 SocketError HasDataAvailable(bool waitForData) const;
136
137 // Client socket
138 bool CreateClient(unsigned short socketPort, bool nonBlockingConnection = false, const CXString& address = _T("localhost")); // Create a client socket. If socket handle is not null, check that the server is still available. If not close and reinit the socket
139
140 // Server socket
141 bool CreateServer(unsigned short socketPort, unsigned int maxClientCount, bool startListening = true);
142 bool StartListening(); // Start async server listening in a different thread.
143 bool StopListening(bool wait); // Stop server listening in a different thread.
144 unsigned int GetMaxClient() const { return maxClient; } // The maximum allowed clients
145 const xSocket *GetClients(unsigned int& clientNbr) const; // Return the client socket and the client nbr
146
147 // Memory features
148 static void Free(void *data); // This free a memory block returned by ReadData for example.
149};
150
151END_MOOTOOLS_NAMESPACE
152
153#endif // !defined(XSOCKET_H)
The class defines an x, y, z 3D point which can use int, float or double.
Definition 3DPoint.h:27
CCustomData is a handly class for storing any kind of data.
Definition CustomData.h:106
Definition XSocket.h:28
Definition XThread.h:14
Definition XSocket.h:40