-
Notifications
You must be signed in to change notification settings - Fork 9
/
EasySocket.cpp
379 lines (320 loc) · 11.7 KB
/
EasySocket.cpp
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// EasySocket
// ysbbs
// This file contains the definitions for the three socket classes: Basic, Data, and Listening.
#include "EasySocket.h"
namespace SocketLib
{
// ========================================================================
// This class is designed to be a global singleton that initializes
// and shuts down Winsock.
// ========================================================================
#ifdef _WIN32 // windows
class System
{
public:
// ================================================================
// This initializes winsock
// ================================================================
System()
{
// attempt to start up the winsock lib
WSAStartup(MAKEWORD(2, 2), &m_WSAData);//windows need this
}
// ========================================================================
// This shuts down winsock
// ========================================================================
~System()
{
// attempt to close down the winsock lib
WSACleanup();//结束API工作
}
protected:
// holds information about winsock
WSADATA m_WSAData;
};
System g_system;//这里实例化了个API初始化对象,使程序在using socket namespace时候就默认的初始化API,结束时自动析构,自动结束API工作
//放在这里不和程序其它任何地方的命名冲突
#endif
// ====================================================================
// Function: Close
// Purpose: closes the socket.
// ====================================================================
void Socket::Close()
{
// WinSock uses "closesocket" instead of "close", since it treats
// sockets as completely separate objects to files, whereas unix
// treats files and sockets exactly the same.
#ifdef _WIN32
closesocket( m_sock );
#else
close( m_sock );
#endif
// invalidate the socket
m_sock = -1;
}
// ====================================================================
// Function: SetBlocking
// Purpose: sets whether the socket is blocking or not.
// ====================================================================
void Socket::SetBlocking( bool p_blockmode )
{
int err;
#ifdef _WIN32
unsigned long mode = !p_blockmode;
err = ioctlsocket( m_sock, FIONBIO, &mode );
#else
// get the flags
int flags = fcntl( m_sock, F_GETFL, 0 );
// set or clear the non-blocking flag
if( p_blockmode == false )
{
flags |= O_NONBLOCK;
}
else
{
flags &= ~O_NONBLOCK;
}
err = fcntl( m_sock, F_SETFL, flags );
#endif
if( err == -1 )
{
throw( Exception( GetError() ) );
}
m_isblocking = p_blockmode;
}
// ====================================================================
// Function: BasicSocket
// Purpose: hidden constructor, meant to prevent people from
// instantiating this class. You should be using direct
// implementations of this class instead, such as
// ListeningSocket and DataSocket.
// ====================================================================
Socket::Socket( sock p_socket ): m_sock( p_socket )
{
if( p_socket != -1 )
{
socklen_t s = sizeof(m_localinfo);
getsockname( p_socket, (sockaddr*)(&m_localinfo), &s );
}
// the socket is blocking by default
m_isblocking = true;
}
// ====================================================================
// Function: DataSocket
// Purpose: Constructs the data socket with optional values
// ====================================================================
DataSocket::DataSocket( sock p_socket ) : Socket( p_socket ),m_connected( false )
{
if( p_socket != -1 )
{
socklen_t s = sizeof(m_remoteinfo);
getpeername( p_socket, (sockaddr*)(&m_remoteinfo), &s );
m_connected = true;
}
}
// ====================================================================
// Function: Connect
// Purpose: Connects this socket to another socket. This will fail
// if the socket is already connected, or the server
// rejects the connection.
// ====================================================================
void DataSocket::Connect( ipaddress p_addr, port p_port )
{
int err;
// if the socket is already connected...
if( m_connected == true )
{
throw Exception( EAlreadyConnected );
}
// first try to obtain a socket descriptor from the OS, if
// there isn't already one.
if( m_sock == -1 )
{
m_sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
// throw an exception if the socket could not be created
if( m_sock == -1 )
{
throw Exception( GetError() );
}
}
// set up the socket address structure
m_remoteinfo.sin_family = AF_INET;
m_remoteinfo.sin_port = htons( p_port );
m_remoteinfo.sin_addr.s_addr = p_addr;
memset( &(m_remoteinfo.sin_zero), 0, 8 );
// now the socket is created, so connect it.
socklen_t s = sizeof(struct sockaddr);
err = connect( m_sock, (struct sockaddr*)(&m_remoteinfo), s );
if( err == -1 )
{
throw Exception( GetError() );
}
m_connected = true;
// to get the local port, you need to do a little more work
err = getsockname( m_sock, (struct sockaddr*)(&m_localinfo), &s );
if( err != 0 )
{
throw Exception( GetError() );
}
}
// ====================================================================
// Function: Send
// Purpose: Attempts to send data, and returns the number of
// of bytes sent
// ====================================================================
int DataSocket::Send( const char* p_buffer, int p_size )
{
int err;
// make sure the socket is connected first.
if( m_connected == false )
{
throw Exception( ENotConnected );
}
// attempt to send the data
err = send( m_sock, p_buffer, p_size, 0 );
if( err == -1 )
{
Error e = GetError();
if( e != EOperationWouldBlock )
{
throw Exception( e );
}
// if the socket is nonblocking, we don't want to send a terminal
// error, so just set the number of bytes sent to 0, assuming
// that the client will be able to handle that.
err = 0;
}
// return the number of bytes successfully sent
return err;
}
// ====================================================================
// Function: Receive
// Purpose: Attempts to recieve data from a socket, and returns the
// amount of data received.
// ====================================================================
int DataSocket::Receive( char* p_buffer, int p_size )
{
int err;
// make sure the socket is connected first.
if( m_connected == false )
{
throw Exception( ENotConnected );
}
// attempt to recieve the data
err = recv( m_sock, p_buffer, p_size, 0 );
if( err == 0 )
{
throw Exception( EConnectionClosed );
}
if( err == -1 )
{
throw Exception( GetError() );
}
// return the number of bytes successfully recieved
return err;
}
// ====================================================================
// Function: Close
// Purpose: closes the socket.
// ====================================================================
void DataSocket::Close()
{
if( m_connected == true )
{
shutdown( m_sock, 2 );
}
// close the socket
Socket::Close();
m_connected = false;
}
// ====================================================================
// Function: ListeningSocket
// Purpose: Constructor. Constructs the socket with initial values
// ====================================================================
ListeningSocket::ListeningSocket()
{
m_listening = false;
}
// ====================================================================
// Function: Listen
// Purpose: this function will tell the socket to listen on a
// certain port
// p_port: This is the port that the socket will listen on.
// ====================================================================
void ListeningSocket::Listen( port p_port )
{
int err;
// first try to obtain a socket descriptor from the OS, if
// there isn't already one.
if( m_sock == -1 )
{
m_sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
// throw an exception if the socket could not be created
if( m_sock == -1 )
{
throw Exception( GetError() );
}
}
// set the SO_REUSEADDR option on the socket, so that it doesn't
// hog the port after it closes.
int reuse = 1;
err = setsockopt( m_sock, SOL_SOCKET, SO_REUSEADDR,
(char*)(&reuse), sizeof( reuse ) );
if( err != 0 )
{
throw Exception( GetError() );
}
// set up the socket address structure
m_localinfo.sin_family = AF_INET;
m_localinfo.sin_port = htons( p_port );
m_localinfo.sin_addr.s_addr = htonl( INADDR_ANY );
memset( &(m_localinfo.sin_zero), 0, 8 );
// bind the socket
err = bind( m_sock, (struct sockaddr*)&m_localinfo,
sizeof(struct sockaddr));
if( err == -1 )
{
throw Exception( GetError() );
}
// now listen on the socket. There is a very high chance that this will
// be successful if it got to this point, but always check for errors
// anyway. Set the queue to 8; a reasonable number.
err = listen( m_sock, 8 );
if( err == -1 )
{
throw Exception( GetError() );
}
m_listening = true;
}
// ====================================================================
// Function: Accept
// Purpose: This is a blocking function that will accept an
// incomming connection and return a data socket with info
// about the new connection.
// ====================================================================
DataSocket ListeningSocket::Accept()
{
sock s;
struct sockaddr_in socketaddress;
// try to accept a connection
socklen_t size = sizeof(struct sockaddr);
s = accept( m_sock, (struct sockaddr*)&socketaddress, &size );
if( s == -1 )
{
throw Exception( GetError() );
}
// return the newly created socket.
return DataSocket( s );
}
// ====================================================================
// Function: Close
// Purpose: closes the socket.
// ====================================================================
void ListeningSocket::Close()
{
// close the socket
Socket::Close();
// invalidate the variables
m_listening = false;
}
} // end namespace SocketLib