-
Notifications
You must be signed in to change notification settings - Fork 3
/
sock_wrap.cpp
475 lines (433 loc) · 14.1 KB
/
sock_wrap.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
#include "platform.h"
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include "lightthread.h"
#include "sock_wrap.h"
#include "TimeSpan.h"
#define INVALIDSOCKHANDLE INVALID_SOCKET
#if defined(_WIN32_PLATFROM_)
#include <windows.h>
#define ISSOCKHANDLE(x) (x!=INVALID_SOCKET)
#define BLOCKREADWRITE 0
#define NONBLOCKREADWRITE 0
#define SENDNOSIGNAL 0
#define ETRYAGAIN(x) (x==WSAEWOULDBLOCK||x==WSAETIMEDOUT)
#define gxsprintf sprintf_s
#endif
#if defined(_LINUX_PLATFORM_)
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define ISSOCKHANDLE(x) (x>0)
#define BLOCKREADWRITE MSG_WAITALL
#define NONBLOCKREADWRITE MSG_DONTWAIT
#define SENDNOSIGNAL MSG_NOSIGNAL
#define ETRYAGAIN(x) (x==EAGAIN||x==EWOULDBLOCK)
#define gxsprintf snprintf
#endif
void GetAddressFrom(sockaddr_in *addr, const char *ip, int port)
{
memset(addr, 0, sizeof(sockaddr_in));
addr->sin_family = AF_INET; /*地址类型为AF_INET*/
if(ip)
{
addr->sin_addr.s_addr = inet_addr(ip);
}
else
{
/*网络地址为INADDR_ANY,这个宏表示本地的任意IP地址,因为服务器可能有多个网卡,每个网卡也可能绑定多个IP地址,
这样设置可以在所有的IP地址上监听,直到与某个客户端建立了连接时才确定下来到底用哪个IP地址*/
addr->sin_addr.s_addr = htonl(INADDR_ANY);
}
addr->sin_port = htons(port); /*端口号*/
}
void GetIpAddress(char *ip, sockaddr_in *addr)
{
unsigned char *p =(unsigned char *)( &(addr->sin_addr));
gxsprintf(ip, 17, "%u.%u.%u.%u", *p,*(p+1), *(p+2), *(p+3) );
}
int GetLastSocketError()
{
#if defined(_WIN32_PLATFROM_)
return WSAGetLastError();
#endif
#if defined(_LINUX_PLATFORM_)
return errno;
#endif
}
bool IsValidSocketHandle(HSocket handle)
{
return ISSOCKHANDLE(handle);
}
void SocketClose(HSocket &handle)
{
if(ISSOCKHANDLE(handle))
{
#if defined(_WIN32_PLATFROM_)
closesocket(handle);
#endif
#if defined(_LINUX_PLATFORM_)
close(handle);
#endif
handle = INVALIDSOCKHANDLE;
}
}
HSocket SocketOpen(int tcpudp)
{
int protocol = 0;
HSocket hs;
#if defined(_WIN32_PLATFROM_)
if(tcpudp== SOCK_STREAM) protocol=IPPROTO_TCP;
else if (tcpudp== SOCK_DGRAM) protocol = IPPROTO_UDP;
#endif
hs = socket(AF_INET, tcpudp, protocol);
return hs;
}
int SocketBind(HSocket hs, sockaddr_in *paddr)
{
return bind(hs, (struct sockaddr *)paddr, sizeof(sockaddr_in));
}
int SocketListen(HSocket hs, int maxconn)
{
return listen(hs,maxconn);
}
HSocket SocketAccept(HSocket hs, sockaddr_in *paddr)
{
#if defined(_WIN32_PLATFROM_)
int cliaddr_len = sizeof(sockaddr_in);
#endif
#if defined(_LINUX_PLATFORM_)
socklen_t cliaddr_len = sizeof(sockaddr_in);
#endif
return accept(hs, (struct sockaddr *)paddr, &cliaddr_len);
}
//
// if timeout occurs, nbytes=-1, nresult=1
// if socket error, nbyte=-1, nresult=-1
// if the other side has disconnected in either block mode or nonblock mode, nbytes=0, nresult=-1
// otherwise nbytes= the count of bytes sent , nresult=0
void SocketSend(HSocket hs, const char *ptr, int nbytes, transresult_t &rt)
{
rt.nbytes = 0;
rt.nresult = 0;
if(!ptr|| nbytes<1) return;
//Linux: flag can be MSG_DONTWAIT, MSG_WAITALL, 使用MSG_WAITALL的时候, socket 必须是处于阻塞模式下,否则WAITALL不能起作用
rt.nbytes = send(hs, ptr, nbytes, BLOCKREADWRITE|SENDNOSIGNAL);
if(rt.nbytes>0)
{
rt.nresult = (rt.nbytes == nbytes)?0:1;
}
else if(rt.nbytes==0)
{
rt.nresult=-1;
}
else
{
rt.nresult = GetLastSocketError();
rt.nresult = ETRYAGAIN(rt.nresult)? 1:-1;
}
}
// if timeout occurs, nbytes=-1, nresult=1
// if socket error, nbyte=-1, nresult=-1
// if the other side has disconnected in either block mode or nonblock mode, nbytes=0, nresult=-1
void SocketRecv(HSocket hs, char *ptr, int nbytes, transresult_t &rt)
{
rt.nbytes = 0;
rt.nresult = 0;
if(!ptr|| nbytes<1) return;
rt.nbytes = recv(hs, ptr, nbytes, BLOCKREADWRITE);
if(rt.nbytes>0)
{
return;
}
else if(rt.nbytes==0)
{
rt.nresult=-1;
}
else
{
rt.nresult = GetLastSocketError();
rt.nresult = ETRYAGAIN(rt.nresult)? 1:-1;
}
}
// nbytes= the count of bytes sent
// if timeout occurs, nresult=1
// if socket error, nresult=-1,
// if the other side has disconnected in either block mode or nonblock mode, nresult=-2
void SocketTrySend(HSocket hs, const char *ptr, int nbytes, int milliseconds, transresult_t &rt)
{
rt.nbytes = 0;
rt.nresult = 0;
if(!ptr|| nbytes<1) return;
int n;
CMyTimeSpan start;
while(1)
{
n = send(hs, ptr+rt.nbytes, nbytes, NONBLOCKREADWRITE|SENDNOSIGNAL);
if(n>0)
{
rt.nbytes += n;
nbytes -= n;
if(rt.nbytes >= nbytes) { rt.nresult = 0; break; }
}
else if( n==0)
{
rt.nresult= -2;
break;
}
else
{
n = GetLastSocketError();
if(ETRYAGAIN(n))
{
CLightThread::DiscardTimeSlice();
}
else
{
rt.nresult = -1;
break;
}
}
if(start.GetSpaninMilliseconds()>milliseconds) { rt.nresult= 1; break;}
}
}
// if timeout occurs, nbytes=-1, nresult=1
// if socket error, nbyte=-1, nresult=-1
// if the other side has disconnected in either block mode or nonblock mode, nbytes=0, nresult=-1
void SocketTryRecv(HSocket hs, char *ptr, int nbytes, int milliseconds, transresult_t &rt)
{
rt.nbytes = 0;
rt.nresult = 0;
if(!ptr|| nbytes<1) return;
if(milliseconds>2)
{
CMyTimeSpan start;
while(1)
{
rt.nbytes = recv(hs, ptr, nbytes, NONBLOCKREADWRITE);
if(rt.nbytes>0)
{
break;
}
else if(rt.nbytes==0)
{
rt.nresult = -1;
break;
}
else
{
rt.nresult = GetLastSocketError();
if( ETRYAGAIN(rt.nresult))
{
if(start.GetSpaninMilliseconds()>milliseconds) { rt.nresult= 1; break;}
CLightThread::DiscardTimeSlice();
}
else
{
rt.nresult = -1;
break;
}
}
}
}
else
{
SocketRecv(hs, ptr, nbytes, rt);
}
}
void SocketClearRecvBuffer(HSocket hs)
{
#if defined(_WIN32_PLATFROM_)
struct timeval tmOut;
tmOut.tv_sec = 0;
tmOut.tv_usec = 0;
fd_set fds;
FD_ZERO(&fds);
FD_SET(hs, &fds);
int nRet = 1;
char tmp[100];
int rt;
while(nRet>0)
{
nRet= select(FD_SETSIZE, &fds, NULL, NULL, &tmOut);
if(nRet>0)
{
nRet = recv(hs, tmp, 100,0);
}
}
#endif
#if defined(_LINUX_PLATFORM_)
char tmp[100];
while(recv(hs, tmp, 100, NONBLOCKREADWRITE)> 0);
#endif
}
int SocketBlock(HSocket hs, bool bblock)
{
unsigned long mode;
if( ISSOCKHANDLE(hs))
{
#if defined(_WIN32_PLATFROM_)
mode = bblock?0:1;
return ioctlsocket(hs,FIONBIO,&mode);
#endif
#if defined(_LINUX_PLATFORM_)
mode = fcntl(hs, F_GETFL, 0); //获取文件的flags值。
//设置成阻塞模式 非阻塞模式
return bblock?fcntl(hs,F_SETFL, mode&~O_NONBLOCK): fcntl(hs, F_SETFL, mode | O_NONBLOCK);
#endif
}
return -1;
}
int SocketTimeOut(HSocket hs, int recvtimeout, int sendtimeout, int lingertimeout) //in milliseconds
{
int rt=-1;
if (ISSOCKHANDLE(hs) )
{
rt=0;
#if defined(_WIN32_PLATFROM_)
if(lingertimeout>-1)
{
struct linger lin;
lin.l_onoff = lingertimeout;
lin.l_linger = lingertimeout ;
rt = setsockopt(hs,SOL_SOCKET,SO_DONTLINGER,(const char*)&lin,sizeof(linger)) == 0 ? 0:0x1;
}
if(recvtimeout>0 && rt == 0)
{
rt = rt | (setsockopt(hs,SOL_SOCKET,SO_RCVTIMEO,(char *)&recvtimeout,sizeof(int))==0?0:0x2);
}
if(sendtimeout>0 && rt == 0)
{
rt = rt | (setsockopt(hs,SOL_SOCKET, SO_SNDTIMEO, (char *)&sendtimeout,sizeof(int))==0?0:0x4);
}
#endif
#if defined(_LINUX_PLATFORM_)
struct timeval timeout;
if(lingertimeout>-1)
{
struct linger lin;
lin.l_onoff = lingertimeout>0?1:0;
lin.l_linger = lingertimeout/1000 ;
rt = setsockopt(hs,SOL_SOCKET,SO_LINGER,(const char*)&lin,sizeof(linger)) == 0 ? 0:0x1;
}
if(recvtimeout>0 && rt == 0)
{
timeout.tv_sec = recvtimeout/1000;
timeout.tv_usec = (recvtimeout % 1000)*1000;
rt = rt | (setsockopt(hs,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout))==0?0:0x2);
}
if(sendtimeout>0 && rt == 0)
{
timeout.tv_sec = sendtimeout/1000;
timeout.tv_usec = (sendtimeout % 1000)*1000;
rt = rt | (setsockopt(hs,SOL_SOCKET, SO_SNDTIMEO, &timeout,sizeof(timeout))==0?0:0x4);
}
#endif
}
return rt;
}
int InitializeSocketEnvironment()
{
#if defined(_WIN32_PLATFROM_)
WSADATA Ws;
//Init Windows Socket
if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 )
{
return -1;
}
#endif
return 0;
}
void FreeSocketEnvironment()
{
#if defined(_WIN32_PLATFROM_)
WSACleanup();
#endif
}
//==============================================================================================================
//================================================================================================================
CSockWrap::CSockWrap(int tcpudp)
{
memset(&m_stAddr, 0, sizeof(sockaddr_in));
m_tcpudp = tcpudp;
m_hSocket = INVALIDSOCKHANDLE;
Reopen(false);
}
CSockWrap::~CSockWrap()
{
SocketClose(m_hSocket);
}
void CSockWrap::Reopen(bool bForceClose)
{
if (ISSOCKHANDLE(m_hSocket) && bForceClose) SocketClose(m_hSocket);
if (!ISSOCKHANDLE(m_hSocket) )
{
m_hSocket=SocketOpen(m_tcpudp);
}
}
void CSockWrap::SetAddress(const char *ip, int port)
{
GetAddressFrom(&m_stAddr, ip, port);
}
void CSockWrap::SetAddress(sockaddr_in *addr)
{
memcpy(&m_stAddr, addr, sizeof(sockaddr_in));
}
int CSockWrap::SetTimeOut(int recvtimeout, int sendtimeout, int lingertimeout) //in milliseconds
{
return SocketTimeOut(m_hSocket, recvtimeout, sendtimeout, lingertimeout);
}
int CSockWrap::SetBufferSize(int recvbuffersize, int sendbuffersize) //in bytes
{
int rt=-1;
if (ISSOCKHANDLE(m_hSocket) )
{
#if defined(_WIN32_PLATFROM_)
if(recvbuffersize>-1)
{
rt = setsockopt( m_hSocket, SOL_SOCKET, SO_RCVBUF, ( const char* )&recvbuffersize, sizeof( int ) );
}
if(sendbuffersize>-1)
{
rt = rt | (setsockopt(m_hSocket,SOL_SOCKET,SO_SNDBUF,(char *)&sendbuffersize,sizeof(int))==0?0:0x2);
}
#endif
}
return rt;
}
int CSockWrap::SetBlock(bool bblock)
{
return SocketBlock(m_hSocket, bblock);
}
transresult_t CSockWrap::Send(void *ptr, int nbytes)
{
transresult_t rt;
SocketSend(m_hSocket, (const char *)ptr, nbytes,rt);
return rt;
}
transresult_t CSockWrap::Recv(void *ptr, int nbytes )
{
transresult_t rt;
SocketRecv(m_hSocket, (char *)ptr, nbytes,rt);
return rt;
}
transresult_t CSockWrap::TrySend(void *ptr, int nbytes, int milliseconds)
{
transresult_t rt;
SocketTrySend(m_hSocket, (const char *)ptr, nbytes,milliseconds, rt);
return rt;
}
transresult_t CSockWrap::TryRecv(void *ptr, int nbytes, int milliseconds )
{
transresult_t rt;
SocketTryRecv(m_hSocket, (char *)ptr, nbytes,milliseconds, rt);
return rt;
}
void CSockWrap::ClearRecvBuffer()
{
SocketClearRecvBuffer(m_hSocket);
}