单军华
2017-07-12 20d1260d26b028897f3c0935c12fc35aa37b2e93
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//
//  ClientSocket.h
//  GoldRich
//
//  Created by WindShan on 2017/3/8.
//  Copyright © 2017年 WindShan. All rights reserved.
//
 
#ifndef ClientSocket_h
#define ClientSocket_h
 
#include <sys/socket.h>
#include <fcntl.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
 
#define SOCKET unsigned int
#define SOCKET_ERROR   -1
#define INVALID_SOCKET -1
 
#include "pthread.h"
#include "IClientSocket.h"
 
 
#define call_func_no_param(f) if(f != nullptr){f();}
#define call_func_one_param(f,p) if(f != nullptr){f(p);}
 
#include "NetStream.h"
 
#ifndef INADDR_NONE
#define INADDR_NONE 0xffffffff
#endif // !INADDR_NONE
 
enum connect_status
{
    con_status_ing = 1,
    con_status_suc = 0,
    con_status_err = -1,
    con_status_timeout = -2,
    
    con_status_called_err = -100,
    con_status_called_timeout = -101,
};
 
 
static int init_sock_reference = 0;
typedef struct __package
{
    int size;
    char* buf;
}send_package,rec_package;
 
 
class CClientSocket
{
public:
    CClientSocket(void)
    :success_call(nullptr),
    timeout_call(nullptr),
    error_call(nullptr),
    receive_call(nullptr),
    socket_handle(INVALID_SOCKET),
    out_time(20),
    ser_addr(0),
    ser_port(0)
    {
        con_status = con_status_err;
        
        def_recbuf_size  = 64*1024;
        def_sendbuf_size = 64*1024;
        
        def_buf = new char[def_recbuf_size];
        memset(def_buf,0,def_recbuf_size);
        
        pRecStream = new CNetStream;
    }
    
    ~CClientSocket(void)
    {
        success_call    = nullptr;
        error_call        = nullptr;
        timeout_call    = nullptr;
        receive_call    = nullptr;
        
        if (socket_handle != INVALID_SOCKET)
        {
            Close();
            socket_handle = INVALID_SOCKET;
        }
        
        if (pRecStream)
        {
            pRecStream->detach();
            delete pRecStream;
        }
        
        if (def_buf)
        {
            delete []def_buf;
            def_buf = nullptr;
        }
        
        for (list<send_package>::iterator i = lst_send.begin();i != lst_send.end();i++)
        {
            ClosePkg(*i);
        }
        lst_send.clear();
    }
public:
    static int  InitSockEnv()
    {
        init_sock_reference++;
        
        return 1;
    }
    
    static void UninitSockEnv()
    {
        init_sock_reference--;
    }
public:
    int Connect(const char* ip,short port,int outTime,on_connect_success sc,on_connect_time_out tm,on_connect_error er,on_receive_package re)
    {
        
        Clear();
        
        success_call    = sc;
        timeout_call    = tm;
        error_call        = er;
        receive_call    = re;
        
        ser_addr = inet_addr(ip);
        ser_port = port;
        out_time = outTime;
        if (ip == 0 || strlen(ip) > 15 || ser_addr == INADDR_NONE)
        {
            con_status = con_status_err;
            call_func_no_param(error_call);
            con_status = con_status_called_err;
            return -1;
        }
        
        
        socket_handle = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
        if (socket_handle == INVALID_SOCKET)
        {
            Close();
            con_status = con_status_err;
            call_func_no_param(error_call);
            con_status = con_status_called_err;
            
            return -1;
        }
        
        
        int nRes = 0;
#ifdef WIN32
        unsigned long mod = 1;
        nRes = ioctlsocket(socket_handle,FIONBIO,&mod);
#else
        // 设置为非阻塞方式
        nRes = fcntl(socket_handle,F_SETFL,O_NONBLOCK);
#endif
        
        if (nRes < 0 )
        {
            Close();
            con_status = con_status_err;
            call_func_no_param(error_call);
            con_status = con_status_called_err;
            
            return -1;
        }
        
        con_status = con_status_ing;
        pthread_create(&t_id,nullptr,connect_thread_func,this);
        
        
        return 1;
    }
    int SendStream(CNetStream* pStream)
    {
        if (pStream == nullptr){
            return -1;
        }
        
        return CreateNewPkg(pStream->getLenth(),pStream->getData());
    }
    int Close()
    {
        return close(m_sockClient);
    }
    
    
    //you should call this function in circle
    void process()
    {
        DoReceive();
        
        CheckErr();
        
        switch (con_status)
        {
            case con_status_suc:
            {
                Flush();
                break;
            }
            case con_status_err:
            {
                call_func_no_param(error_call);
                con_status = con_status_called_err;
                break;
            }
            case con_status_called_err:
                break;
            case con_status_ing:
                break;
            case con_status_timeout:
                break;
            case con_status_called_timeout:
                break;
                
            default:
                break;
        }
        
    }
    
private:
    int GetError()
    {
        int err = 0;
#ifdef WIN32
        err = WSAGetLastError();
        if(err != WSAEWOULDBLOCK) {
#else
            err = errno;
            if(err != EINPROGRESS && err != EAGAIN)
            {
#endif
                return 1;
            }
            
            return 0;
        }
        
        int DoConnectProcess()
    {
        sockaddr_in addr_in;
        memset((void*)&addr_in,0,sizeof(addr_in));
        
        addr_in.sin_family = AF_INET;
        addr_in.sin_port = htons(ser_port);
        addr_in.sin_addr.s_addr = ser_addr;
        
        if (connect(socket_handle,(sockaddr*)&addr_in,sizeof(addr_in)) == SOCKET_ERROR)
        {
            if (GetError() == 1)
            {
                Close();
                con_status = con_status_err;
                /*call_func_no_param(error_call);
                 con_status = con_status_called_err;*/
                
                return -1;
            }
            
            timeval timeout;
            timeout.tv_sec    = out_time;
            timeout.tv_usec    = 0;
            fd_set writeset,exceptset;
            FD_ZERO(&writeset);
            FD_ZERO(&exceptset);
            FD_SET(socket_handle,&writeset);
            FD_SET(socket_handle,&exceptset);
            
            int ret = select(FD_SETSIZE,nullptr,&writeset,&exceptset,&timeout);
            if (ret < 0)
            {
                Close();
                con_status = con_status_err;
                /*call_func_no_param(error_call);
                 con_status = con_status_called_err;*/
                
                return -1;
            }
            else if (ret == 0)
            {
                Close();
                con_status = con_status_timeout;
                call_func_no_param(timeout_call);
                con_status = con_status_called_timeout;
            }
            
            ret = FD_ISSET(socket_handle,&exceptset);
            if(ret){
                Close();
                con_status = con_status_err;
                /*call_func_no_param(error_call);
                 con_status = con_status_called_err;*/
                
                return -1;
            }
        }
        
        struct linger so_linger;
        so_linger.l_onoff  = 1;
        so_linger.l_linger = 5;
        
        setsockopt(socket_handle,SOL_SOCKET,SO_LINGER,(const char*)&so_linger,sizeof(so_linger));
        setsockopt(socket_handle,SOL_SOCKET,SO_RCVBUF,(const char*)&def_recbuf_size,sizeof(int));
        setsockopt(socket_handle,SOL_SOCKET,SO_SNDBUF,(const char*)&def_sendbuf_size,sizeof(int));
        
        con_status = con_status_suc;
        call_func_no_param(success_call);
        
        
        return 1;
    }
    static void* connect_thread_func(void* arg)
    {
        CClientSocket* pObj = (CClientSocket*)arg;
        if (pObj != nullptr)
        {
            pObj->DoConnectProcess();
        }
        
        return 0;
    }
    
    int CheckErr()
        {
            if (con_status == con_status_ing){
                return -1;
            }
            
            if (con_status == con_status_called_err || con_status == con_status_called_timeout){
                con_status = con_status_called_err;
                return -1;
            }
            
            if (socket_handle == INVALID_SOCKET || con_status == con_status_err){
                con_status = con_status_err;
                return -1;
            }
            
            char buf[1];
            int nRet = recv(socket_handle,buf,1,MSG_PEEK);
            if(nRet == 0)
            {
                Close();
                con_status = con_status_err;
                
                return -1;
            }
            else if(nRet < 0) 
            {
                if (GetError() == 1) 
                {
                    Close();
                    con_status = con_status_err;
                    
                    return -1;
                }
            }
            
            con_status = con_status_suc;
            
            return 1;
        }
        
    int CreateNewPkg(int size,const char* buf)
        {
            if (size > 0 && buf != nullptr)
            {
                send_package pkg;
                pkg.size = size;
                pkg.buf = new char[size];
                memcpy(pkg.buf,buf,pkg.size);
                lst_send.push_back(pkg);
                
                return 1;
            }
            
            return -1;
        }
        
    int ClosePkg(send_package& pkg)
        {
            if (pkg.buf)
            {
                delete []pkg.buf;
                pkg.buf = nullptr;
                pkg.size = 0;
                return 1;
            }
            
            return -1;
        }
        
        int Flush()
        {
            if (lst_send.size() > 0) // have send data
            {
                list<send_package>::iterator iPkg = lst_send.begin();
                int sd_size = send(socket_handle,iPkg->buf,iPkg->size,0);
                if (sd_size >= iPkg->size)
                {
                    ClosePkg(*iPkg);
                    lst_send.pop_front();
                    return 1;
                }
                else
                {
                    printf("send err ,data is to larage!>>>>>>");
                    return -1;
                }
            }
            
            return 1;
        }
        
        int DoReceive()
        {
            
            if(con_status != con_status_suc) { return -1; }
            
            int rec_size = recv(socket_handle,def_buf,def_recbuf_size,0);
            
            if (rec_size > 0 )
            {
                pRecStream->attach(def_buf,def_recbuf_size,rec_size);
                call_func_one_param(receive_call,pRecStream);
                pRecStream->detach();
                
                return 1;
            }
            else if (rec_size == 0)
            {
                Close();
                con_status = con_status_err;
                
                return -1;
            }
            else
            {
                if (GetError() == 1)
                {
                    Close();
                    return -1;
                }
            }
            
            return 1;
        }
        
        void Clear()
        {
            if (socket_handle != INVALID_SOCKET){
            Close();
            socket_handle = INVALID_SOCKET;
        }
        
        success_call    = nullptr;
        error_call        = nullptr;
        timeout_call    = nullptr;
        receive_call    = nullptr;
        
        ser_addr = 0;
        ser_port = 0;
        out_time = 20;
        
        if (def_buf != nullptr){
            memset(def_buf,0,def_recbuf_size);
        }
        
        con_status = con_status_err;
        
        for (list<send_package>::iterator i = lst_send.begin();i != lst_send.end();i++)
        {
            ClosePkg(*i);
        }
        lst_send.clear();
    }
    
    
private://member data
    on_connect_success success_call;
    on_connect_time_out timeout_call;
    on_connect_error error_call;
    on_receive_package receive_call;
    
    SOCKET socket_handle;
    
    unsigned long ser_addr;
    short ser_port;
    unsigned long out_time;
    
    int con_status;
    
    int def_recbuf_size;
    int def_sendbuf_size;
    
    char* def_buf;
    CNetStream* pRecStream;
    
    list<send_package> lst_send;
    list<rec_package> lst_rec;
    
    
    
    
    pthread_t t_id;
    pthread_t rec_tid;
};
 
#endif /* ClientSocket_h */