逐步实现TCP服务端Step02-4:两个线程协作

communicator的工作在主线程中进行,再创建一个线程进行process。这个用于process的线程叫“工作线程”。

把主线程中的GetOneMessage和ProcessOneMessage摘出去,至少需要增加如下内容:

  • g_c2s_code_queue - “头”在process侧的code队列
  • g_s2c_code_queue - “头”在communicator侧的code队列
  • PushCodeBack - 入队一个code
  • PopCodeFront - 出队一个code
  • OnRecvdSocketBytes - 处理已recv到的字节,将code入队,如果足够一个code的话
  • GetS2CCode - 检视g_s2c_code_queue队列中等待的code,如果有code的话,将其出队

对工作线程来说,至少还要:

  • EncodeMessage - 将message转成code
  • DecodeMessage - 将code转成message
  • GetC2SCode - 检视g_c2s_code_queue队列中等待的code,如果有code的话,将其出队
  • ProcessOneMessageEx - 新版ProcessOneMessage

其实,目前的SetOneMessage和GetOneMessage就大体等同于EncodeMessage和DecodeMessage的作用。 主线程中的GetS2CCode和工作线程中的GetC2SCode函数应该能支持一次调用出队n(n>=1)个code,按上图的流程,主线程出队n个code是没问题的。工作线程需要改动一下。

当工作线程从g_c2s_code_queue队列中取出一个code后会有两种处理方式,一是立即Decode出Message,然后对其进行Process工作,然后再取下一个code,也就是上图中的流程;二是不立即进行后续的Decode和Process工作,先批量取出n个code,后续再根据需要进行Decode和Process。按照第一种做法,如果Process是一个“长操作”的话,就很有可能导致g_c2s_code_queue队列变满,进而影响communicator的工作。工作线程应尽快将g_c2s_code_queue队列中的code取出,取code的操作不应该与Process耦合在一起。

要令工作线程的GetC2SCode调用一次性出队n个code,我们就应该按照第二种方式来处理。解耦的办法还是跟之前类似,用一个队列把取出的code存起来即可。至于Decode和Process,它俩应该是紧密耦合的,Process之前肯定要完成Decode操作。在实际当中,消息的类型是多样的,每一类消息都需要各自的Decode和Process来处理。增加一个DispatchMessages函数来“分拣”消息,由它来调用相应的Decode和Process函数。

经过上面的讨论,对主要流程进行修改:

下面是新版代码,这里所实现的code队列在逻辑上是循环的。还有,由于到目前为止都没有定义消息的具体格式,在Decode的时候将code全部按照西文字符串来处理:

base.h

  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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
#ifndef __BASE_H__
#define __BASE_H__

#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <cerrno>

#define MSG_PREFIX_LEN          (4)
#define MAX_RECV_BUF_LEN        (128)
#define MAX_POST_BUF_LEN        (128)
#define QUEUE_RESERVED_LEN      (8) // reserved len: Avoid the head-tail
#define MAX_POP_S2C_CODE_NUM    (32)
#define MAX_POP_C2S_CODE_NUM    (32)
#define MAX_DISPATCH_MSG_NUM    (32)
#define MAX_CODE_BUF_LEN        (256)

struct CodeQueue {
    unsigned char* buf;
    int size;
    int begin;
    int end;
};

struct Message {
    char str[512]; 
};

unsigned char g_recv_buf[MAX_RECV_BUF_LEN];
unsigned char g_post_buf[MAX_POST_BUF_LEN];
int g_read_begin = 0;
int g_read_end   = 0;
int g_post_begin = 0;
int g_post_end   = 0;

CodeQueue g_code_queue;
CodeQueue g_c2s_code_queue;
CodeQueue g_s2c_code_queue;

// retval:
//  0 - success
// -1 - sock invalid 
// -2 - recv buf is full
// -3 - client close
// -4 - send error
int RecvBytes(int sock)
{
    if (sock <= 0) 
        return -1;
    if (g_read_begin == g_read_end) {
        g_read_begin = 0;
        g_read_end   = 0;
    }
    int recvd_bytes_cnt = 0;
    int retval = 0;
    do {
        if (g_read_end >= MAX_RECV_BUF_LEN) {
            retval = -2;
            break;
        }
        recvd_bytes_cnt = recv(sock, 
            &g_recv_buf[g_read_end], 
            MAX_RECV_BUF_LEN - g_read_end, 0);
        if (recvd_bytes_cnt > 0) {
            g_read_end += recvd_bytes_cnt;
        } else if (0 == recvd_bytes_cnt) {
            retval = -3;
            break;
        } else if (EAGAIN != errno) {
            retval = -4;
            break;
        }
    } while (recvd_bytes_cnt > 0);
    return retval;
}

int GetOneMessage(unsigned int& len, unsigned char* msg)
{
    if (!msg) return -1;
    int bytes_cnt = g_read_end - g_read_begin;
    if (bytes_cnt <= MSG_PREFIX_LEN)
        return -2;
    int max_buf_len = len;
    len = ntohl(*((int*)&g_recv_buf[g_read_begin]));
    if (len <= 0) {
        g_read_begin = g_read_end = 0;
        return -3;
    }
    if (max_buf_len < len)
        return -4;
    if (int(bytes_cnt - MSG_PREFIX_LEN) < len) {
        // check if the rest of g_recv_buf is enough.
        if (g_read_begin + len + MSG_PREFIX_LEN 
            >= MAX_RECV_BUF_LEN) {
            memmove(g_recv_buf, 
                &g_recv_buf[g_read_begin], bytes_cnt);
            g_read_begin = 0;
            g_read_end = bytes_cnt;
            if (g_read_begin + len + MSG_PREFIX_LEN 
                > MAX_RECV_BUF_LEN) {
                return -5;
            }
        }
        return -6;
    }
    memcpy(msg, &g_recv_buf[g_read_begin + MSG_PREFIX_LEN], len);
    g_read_begin += MSG_PREFIX_LEN;
    g_read_begin += len;
    if (g_read_begin == g_read_end)
        g_read_begin = g_read_end = 0;
    return 0;
}

int SendReservedBytes(int sock)
{
    if (sock <= 0) return -1;
    int sent_bytes = 0;
    int left_bytes = g_post_end - g_post_begin; 
    if (!left_bytes) return 0;
    unsigned char* tmp_post_buf = &g_post_buf[g_post_begin]; 
    while (1) {
        sent_bytes = send(sock, 
            tmp_post_buf, left_bytes, 0);
        if (sent_bytes > 0) {
            tmp_post_buf += sent_bytes;
            left_bytes -= sent_bytes;
            g_post_begin += sent_bytes;
            if (!left_bytes) {
                g_post_begin = g_post_end = 0;
                return 0;
            }
        } else if (sent_bytes < 0) {
            if (EAGAIN == errno)
                return -2;
            else
                return -3;
        } else 
            return -3;
    }
    return 0;
}

int ReserveBytes(int bytes_cnt, const unsigned char* bytes)
{
    int existing_bytes_cnt = g_post_end - g_post_begin;
    if (existing_bytes_cnt + bytes_cnt < MAX_POST_BUF_LEN) {
        if (g_post_begin > 0) {
            memmove(g_post_buf, &g_post_buf[g_post_begin], 
                    existing_bytes_cnt);
            g_post_begin = 0;
        }
        g_post_end = existing_bytes_cnt;
        memcpy(&g_post_buf[g_post_end], bytes, bytes_cnt);
        g_post_end += bytes_cnt;
    } else return -1;
    return 0;
}

int SetOneMessage(unsigned int len, const unsigned char* msg)
{
    int sent_bytes = 0;
    int left_bytes = MSG_PREFIX_LEN + len;
    unsigned char* buf 
        = new unsigned char[left_bytes];
    if (!buf) return -1;
    *((int*)buf) = htonl(len);
    memcpy(&buf[MSG_PREFIX_LEN], msg, len);
    if (ReserveBytes(left_bytes, buf) < 0) {
        delete[] buf;
        return -1;
    }
    return 0;
}

int SendBytes(int sock)
{
    if (sock <= 0) return -1;
    int sent_bytes = 0;
    int left_bytes = g_post_end - g_post_begin; 
    if (!left_bytes) return 0;
    unsigned char* tmp_post_buf = &g_post_buf[g_post_begin]; 
    while (1) {
        sent_bytes = send(sock, 
            tmp_post_buf, left_bytes, 0);
        if (sent_bytes > 0) {
            tmp_post_buf += sent_bytes;
            left_bytes -= sent_bytes;
            g_post_begin += sent_bytes;
            if (!left_bytes) {
                g_post_begin = g_post_end = 0;
                return 0;
            }
        } else if (sent_bytes < 0) {
            if (EAGAIN == errno)
                return -2;
            else
                return -3;
        } else 
            return -3;
    }
    return 0;
}

int SendOneMessageEx(int sock, unsigned int len, const unsigned char* msg)
{    
    if (!len) return -1;
    if (!msg) return -1;
    if (sock <= 0) return -1;
    int sent_bytes = 0;
    int left_bytes = MSG_PREFIX_LEN + len;
    unsigned char* buf 
        = new unsigned char[left_bytes];
    unsigned char* tmpbuf = buf; 
    if (!buf) return -1;
    *((int*)tmpbuf) = htonl(len);
    memcpy(&tmpbuf[MSG_PREFIX_LEN], msg, len);
    int retval = SendReservedBytes(sock);
    if (retval < 0) {
        if (-2 == retval) {
            if (ReserveBytes(left_bytes, tmpbuf) < 0) {
                delete[] buf;
                return -1;
            }
        } else { 
            delete[] buf;
            return -1;
        }
        delete[] buf;
        return -2;
    }
    while (left_bytes > 0) {
        sent_bytes = send(sock, tmpbuf, left_bytes, 0);
        if (sent_bytes > 0) {
            tmpbuf += sent_bytes;
            left_bytes -= sent_bytes;
        } else if (sent_bytes < 0) {
            if (EAGAIN == errno) {
                if (ReserveBytes(left_bytes, tmpbuf) < 0) {
                    delete[] buf;
                    return -1;
                }
                delete[] buf;
                return -2;
            }
        } else { 
            delete[] buf;
            return -1;
        }
    }
    delete[] buf;
    return 0;
}

int SetSockNonBlock(int sock)
{
    if (sock <= 0) return -1;
    int flags = fcntl(sock, F_GETFL, 0);
    if (flags < 0) return -1;
    flags |= O_NONBLOCK;
    return fcntl(sock, F_SETFL, flags);
}

int RecvOneMessage(int sock, unsigned int& len, unsigned char* msg)
{
    if (!len) return -1;
    if (!msg) return -1;
    if (sock <= 0) return -1;
    int recvd_bytes_cnt = 0;
    int total_recvd_bytes_cnt = 0;
    unsigned char prefix[MSG_PREFIX_LEN];
    int max_buf_len = MSG_PREFIX_LEN;
    while (total_recvd_bytes_cnt != MSG_PREFIX_LEN) {
        if ((recvd_bytes_cnt = recv(sock, 
            &prefix[total_recvd_bytes_cnt], 
            max_buf_len - total_recvd_bytes_cnt, 0)) < 0) {
            return -1;
        }
        if (0 == recvd_bytes_cnt) {
            return 0;
        }
        total_recvd_bytes_cnt += recvd_bytes_cnt;
    }
    max_buf_len = len;
    len = ntohl(*((unsigned int*)prefix));
    if (len > max_buf_len) {
        return -1;
    }
    total_recvd_bytes_cnt = 0;
    while (total_recvd_bytes_cnt != len) {
        if ((recvd_bytes_cnt = recv(sock, 
            &msg[total_recvd_bytes_cnt], 
            max_buf_len - total_recvd_bytes_cnt, 0)) < 0) {
            return -1;
        }
        if (0 == recvd_bytes_cnt) {
            return 0;
        }
        total_recvd_bytes_cnt += recvd_bytes_cnt;
    }
    return total_recvd_bytes_cnt + MSG_PREFIX_LEN;
}

int SendOneMessage(int sock, unsigned int len, const unsigned char* msg)
{    
    if (!len) return -1;
    if (!msg) return -1;
    if (sock <= 0) return -1;
    int total_sent_bytes_cnt = 0;
    unsigned char* buf 
        = new unsigned char[MSG_PREFIX_LEN + len];
    unsigned char* tmpbuf = buf; 
    if (!buf) return -1;
    *((int*)tmpbuf) = htonl(len);
    memcpy(&tmpbuf[MSG_PREFIX_LEN], msg, len);
    len += MSG_PREFIX_LEN;
    if ((total_sent_bytes_cnt 
        = send(sock, tmpbuf, len, 0)) < 0) {
        delete[] buf;
        return -1;
    }
    delete[] buf;
    return total_sent_bytes_cnt;
}

int InitCodeQueue(CodeQueue& code_queue, int size)
{
    unsigned char* buf 
        = new unsigned char[size];
    if (!buf) {
        return -1;
    }
    code_queue.end   = 0;
    code_queue.begin = 0;
    code_queue.buf   = buf;
    code_queue.size  = size;
    return 0;
}

int GetCodeQueueIndexData(CodeQueue& code_queue, int& begin, int& end)
{
    begin = code_queue.begin;
    end = code_queue.end;
    return 0;
}

bool IsCodeQueueFull(CodeQueue& code_queue)
{
    int free_size = 0;
    int begin_idx = -1;
    int end_idx = -1;
    GetCodeQueueIndexData(code_queue, begin_idx, end_idx);
    if (begin_idx == end_idx) {
        free_size = code_queue.size;
    } else if (begin_idx > end_idx) {
        free_size = begin_idx - end_idx;
    } else {
        free_size = code_queue.size - (end_idx - begin_idx);
    }
    free_size -= QUEUE_RESERVED_LEN;
    if (free_size > 0) {
        return false;
    } else {
        return true;
    }
    return 0;
}

int SetCodeQueueIndexData(CodeQueue& code_queue, int begin, int end)
{
    if (begin >= 0 && begin < code_queue.size)
        code_queue.begin = begin;
    if (end >= 0 && end < code_queue.size)
        code_queue.end = end;
    return 0;
}

// retval:
//  0 - success
// -1 - para invalid 
// -2 - not enough
int PushCodeBack(CodeQueue& code_queue, const unsigned char* code, int len)
{
    int begin_idx = -1;
    int end_idx = -1;
    int free_size = 0;
    unsigned char* src = NULL;
    unsigned char* dst = NULL;
    if (!code || len <= 0) 
        return -1;
    if (code_queue.size <= 0 || !code_queue.buf)
        return -1;
    if (IsCodeQueueFull(code_queue))
        return -2;
    GetCodeQueueIndexData(code_queue, begin_idx, end_idx);
    if (begin_idx < 0 || end_idx < 0 
        || begin_idx >= code_queue.size 
        || end_idx >= code_queue.size) {
        end_idx = begin_idx;
        // just update end index.
        SetCodeQueueIndexData(code_queue, -1, end_idx);
        return -1;
    }
    if (begin_idx == end_idx) {
        free_size = code_queue.size;
    } else if (begin_idx > end_idx) {
        free_size = begin_idx - end_idx;
    } else {
        free_size = code_queue.size - (end_idx - begin_idx);
    }
    free_size -= QUEUE_RESERVED_LEN; 
    if ((int)(sizeof(int) + len) > free_size) {
        return -2;
    }
    unsigned char* code_buf = code_queue.buf; 
    dst = &code_buf[0];
    src = (unsigned char*)&len;
    for (int i = 0; i < sizeof(len); i++) {
        dst[end_idx] = src[i]; 
        end_idx = (end_idx + 1) % code_queue.size;
    }
    if (begin_idx > end_idx) {
        memcpy(&code_buf[end_idx], code, len);
    } else {
        if ((int)len > (code_queue.size - end_idx)) {
            memcpy(&code_buf[end_idx], 
                code, code_queue.size - end_idx);
            memcpy(&code_buf[0], &code[code_queue.size - end_idx], 
                len - code_queue.size + end_idx);
        } else {
            memcpy(&code_buf[end_idx], code, len);
        }
    }
    end_idx = (end_idx + len) % code_queue.size;
    // just update end index.
    SetCodeQueueIndexData(code_queue, -1, end_idx);
    return 0;
}

// retval:
//  0 - success
// -1 - para invalid 
// -2 - no code
// -3 - code invalid 
// -4 - out buf not enough 
int PopCodeFront(CodeQueue& code_queue, unsigned char* code, int& len)
{
    int used_size = 0;
    int begin_idx = -1;
    int end_idx = -1;
    int max_out_buf_len = len;
    unsigned char* src = NULL;
    unsigned char* dst = NULL;
    if (!code) {
        len = 0;
        return -1;
    }
    if (!code_queue.buf || code_queue.size <= 0) {
        len = 0;
        return -1;
    }
    unsigned char* code_buf = code_queue.buf;
    GetCodeQueueIndexData(code_queue, begin_idx, end_idx);
    if (begin_idx == end_idx) {
        len = 0;
        return -2;
    }
    if (begin_idx < end_idx) {
        used_size = end_idx - begin_idx;
    } else {
        used_size = code_queue.size - (begin_idx - end_idx);
    }
    if (used_size < sizeof(int)) {
        len = 0;
        begin_idx = end_idx;
        // just update begin index.
        SetCodeQueueIndexData(code_queue, begin_idx, -1);
        return -3;
    }
    src = code_buf;
    dst = (unsigned char*)&len;
    for (int i = 0; i < sizeof(int); i++) {
        dst[i] = src[begin_idx];
        begin_idx = (begin_idx + 1) % code_queue.size;
    }
    if (len > (int)(used_size - sizeof(int)) || len < 0) {
        len = 0;
        begin_idx = end_idx;
        SetCodeQueueIndexData(code_queue, begin_idx, -1);
        return -3;
    }
    if (len > max_out_buf_len) {
        len = 0;
        return -4;
    }
    dst = code;
    if (begin_idx < end_idx) {
        memcpy(dst, &src[begin_idx], len);
    } else {
        if (len > int(code_queue.size - begin_idx)) {
            memcpy(dst, &src[begin_idx], 
                code_queue.size - begin_idx);
            dst += (code_queue.size - begin_idx);
            memcpy(dst, src, 
                len - (code_queue.size - begin_idx));
        } else {
            memcpy(dst, &src[begin_idx], len);
        }
    }
    begin_idx = (begin_idx + len) % code_queue.size;
    // just update begin index.
    SetCodeQueueIndexData(code_queue, begin_idx, -1);
    return 0;
}

int OnRecvdSocketBytes()
{
    int retval = 0;
    int recvd_bytes_cnt 
        = g_read_end - g_read_begin; 
    int need_bytes_cnt = 0;
    if (recvd_bytes_cnt <= MSG_PREFIX_LEN)
        return -2;
    need_bytes_cnt = ntohl(*((int*)&g_recv_buf[g_read_begin]));
    if (need_bytes_cnt <= 0) {
        g_read_begin = g_read_end = 0;
        return -3;
    }
    if (int(recvd_bytes_cnt - MSG_PREFIX_LEN) < need_bytes_cnt) {
        // check if the rest of g_recv_buf is enough.
        if (g_read_begin + need_bytes_cnt + MSG_PREFIX_LEN 
            >= MAX_RECV_BUF_LEN) {
            memmove(g_recv_buf, 
                &g_recv_buf[g_read_begin], recvd_bytes_cnt);
            g_read_begin = 0;
            g_read_end = recvd_bytes_cnt;
            if (g_read_begin + need_bytes_cnt + MSG_PREFIX_LEN 
                >= MAX_RECV_BUF_LEN) {
                return -5;
            }
        }
        return -6;
    }
    if ((retval = PushCodeBack(g_c2s_code_queue, 
        &g_recv_buf[g_read_begin], 
        need_bytes_cnt + MSG_PREFIX_LEN)) < 0) {
        if (-2 == retval) {
            std::clog << "OnRecvdSocketBytes, " 
                << "g_c2s_code_queue is full." 
                << std::endl;
            return -7;
        } else return -8;
    }
    g_read_begin += MSG_PREFIX_LEN;
    g_read_begin += need_bytes_cnt;
    if (g_read_begin == g_read_end)
        g_read_begin = g_read_end = 0;
    return 0;
}

int GetS2CCode()
{
    int retval = 0;
    unsigned char code[MAX_CODE_BUF_LEN];
    int code_len = MAX_CODE_BUF_LEN;
    for (int i = 0; i < MAX_POP_S2C_CODE_NUM; i++) {
        retval = PopCodeFront(g_s2c_code_queue, 
            code, code_len);
        if (retval < 0) {
            if (-1 == retval) {
                std::clog << "GetS2CCode failed, " 
                    << "pop para invalid." << std::endl; 
            } else if (-2 == retval) {
                break;
            } else if (-3 == retval) {
                std::clog << "GetS2CCode failed, " 
                    << "pop code invalid." << std::endl; 
            } else if (-4 == retval) {
                std::clog << "GetS2CCode failed, " 
                    << "pop out code buf not enough." 
                    << std::endl; 
            }
            return -1;
        }
        if (ReserveBytes(code_len, code) < 0) {
            std::clog << "GetS2CCode failed, " 
                << "ReserveBytes failed." 
                << std::endl;
            return -1;
        }
    }
    return 0;
}

int GetC2SCode()
{
    int retval = 0;
    unsigned char code[MAX_CODE_BUF_LEN];
    for (int i = 0; i < MAX_POP_C2S_CODE_NUM; i++) {
        int code_len = MAX_CODE_BUF_LEN;
        memset(code, 0, sizeof(code));
        retval = PopCodeFront(g_c2s_code_queue, 
            code, code_len);
        if (retval < 0) {
            if (-1 == retval) {
                std::clog << "GetC2SCode failed, " 
                    << "pop para invalid." << std::endl; 
            } else if (-2 == retval) {
                break;
            } else if (-3 == retval) {
                std::clog << "GetC2SCode failed, " 
                    << "pop code invalid." << std::endl; 
            } else if (-4 == retval) {
                std::clog << "GetC2SCode failed, " 
                    << "pop out code buf not enough." 
                    << std::endl; 
            }
            return -1;
        }
        if ((retval = PushCodeBack(g_code_queue, 
            code, code_len)) < 0) {
            if (-2 == retval) {
                std::clog << "GetC2SCode, " 
                    << "g_code_queue is full." 
                    << std::endl;
                break;
            }
        }

    }
    return 0;
}

int DecodeMessage(unsigned char* code, int code_len, Message& msg)
{
    if (!code) return -1;
    if (code_len <= 0) return -1;
    memcpy(msg.str, code, sizeof(msg.str));
    return 0;
}

int EncodeMessage(Message& msg, unsigned char* code, int& code_len)
{
    if (!code) return -1;
    if (code_len <= 0) return -1;
    if ((strlen((const char*)msg.str) + MSG_PREFIX_LEN) 
            > code_len) return -1;
    code_len = strlen((const char*)msg.str);
    memcpy(code + MSG_PREFIX_LEN, 
        msg.str, code_len);
    int tmp_code_len = htonl(code_len);
    memcpy(code, &tmp_code_len, MSG_PREFIX_LEN);
    return 0;
}

int ProcessOneMessage(unsigned int len, const unsigned char* msg)
{
    std::clog << msg << std::endl;
    return SetOneMessage(len, msg);
}

int ProcessOneMessageEx(Message& msg)
{
    std::clog <<  msg.str << std::endl;
    unsigned char code[MAX_CODE_BUF_LEN];
    memset(code, 0, sizeof(code));
    int code_len = MAX_CODE_BUF_LEN;
    int retval = EncodeMessage(msg, code, code_len); 
    if (retval < 0) {
        std::clog << "ProcessOneMessageEx, " 
            << "EncodeMessage failed." << std::endl;
        return -1;
    }
    retval = PushCodeBack(g_s2c_code_queue, 
        code, code_len + MSG_PREFIX_LEN);
    if (retval < 0) {
        if (-2 == retval) {
            std::clog << "ProcessOneMessageEx, " 
                << "g_s2c_code_queue is full, " 
                << "current code will be discarded."
                << std::endl;
        } 
        return -1;
    }
    return 0;
}

int DispatchMessages()
{
    int retval = 0;
    unsigned char code[MAX_CODE_BUF_LEN];
    for (int i = 0; i < MAX_DISPATCH_MSG_NUM; i++) {
        int code_len = MAX_CODE_BUF_LEN;
        memset(code, 0, sizeof(code));
        retval = PopCodeFront(g_code_queue, 
            code, code_len);
        if (retval < 0) {
            if (-1 == retval) {
                std::clog << "DispatchMessages failed, " 
                    << "pop para invalid." << std::endl; 
            } else if (-2 == retval) {
                break;
            } else if (-3 == retval) {
                std::clog << "DispatchMessages failed, " 
                    << "pop code invalid." << std::endl; 
            } else if (-4 == retval) {
                std::clog << "DispatchMessages failed, " 
                    << "pop out code buf not enough." 
                    << std::endl; 
            }
            return -1;
        }
        Message msg;
        memset(&msg, 0, sizeof(msg));
        retval = DecodeMessage(code + MSG_PREFIX_LEN, 
            code_len - MSG_PREFIX_LEN, msg);
        if (retval < 0) continue;
        if (ProcessOneMessageEx(msg) < 0) continue;
    }
    return 0;
}

#endif /* __BASE_H__ */

s.cc

  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
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>  
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#include <errno.h>
#include "base.h"

void* ThreadRoutine(void* para)
{
    while (1) {
        if (GetC2SCode() < 0)
            break;
        if (DispatchMessages() < 0)
            break;
    }
    std::clog << "ThreadRoutine, return." 
        << std::endl;  
    return NULL;
}

int main(int argc, char**argv)
{
    if (argc != 2) {
        std::clog << "Usage: " 
            << argv[0] << " port" << std::endl;
        return 0;
    }
    InitCodeQueue(g_code_queue, 100);
    InitCodeQueue(g_c2s_code_queue, 100);
    InitCodeQueue(g_s2c_code_queue, 100);
    memset(g_recv_buf, 0, sizeof(g_recv_buf));
    memset(g_post_buf, 0, sizeof(g_post_buf));
    pthread_t thread_id;
    if (pthread_create(&thread_id, 
        NULL, ThreadRoutine, NULL) != 0) {
        std::cerr << "create thread failed." << std::endl;
        return 1;
    }
    int svr_sock, cli_sock;
    sockaddr_in svr_addr, cli_addr;
    if ((svr_sock = socket(AF_INET, 
        SOCK_STREAM, 0)) < 0) {
        return 1;
    }
    memset(&svr_addr, 0, sizeof(svr_addr));
    svr_addr.sin_family = AF_INET;
    svr_addr.sin_port = htons(atoi(argv[1]));
    svr_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(svr_sock, 
        (const sockaddr*)&svr_addr, 
        sizeof(svr_addr)) < 0) {
        return 1;
    }
    if (listen(svr_sock, 4) < 0) {
        return 1;
    }
    while (1) {
        memset(&cli_addr, 0, sizeof(cli_addr));
        socklen_t addr_len = sizeof(cli_addr);
        if ((cli_sock = accept(svr_sock, 
            (sockaddr*)&cli_addr, &addr_len)) < 0) {
            return 1;
        }
        if (SetSockNonBlock(cli_sock) < 0) {
            std::cerr << "set sock nonblock failed!" << std::endl;
            return 1;
        }
        unsigned char msg[128] = {0};
        while (1) {
            unsigned int msg_len = sizeof(msg);
            memset(msg, 0, msg_len);

            // RecvBytes
            /////////////////////////////////////////////////
            int retval = RecvBytes(cli_sock);
            if (-2 == retval) {
                std::clog << "recv buf is full." << std::endl;
            } else if (-3 == retval) {
                std::clog << "cli close!" << std::endl;
                break;
            } else if (retval < 0) 
                return 1;

            // OnRecvdSocketBytes
            /////////////////////////////////////////////////
            retval = OnRecvdSocketBytes();
            if (retval < 0) {
                if (retval != -2 && retval != -6 
                    && retval != -7) {
                    return 1;
                }
            }

            // GetS2CCode
            /////////////////////////////////////////////////
            retval = GetS2CCode();
            if (retval < 0)
                return 1;

            // SendBytes 
            /////////////////////////////////////////////////
            retval = SendBytes(cli_sock);
            if (retval < 0) {
                if (-2 == retval) {
                    continue;
                }
                return 1;
            }
        }
        close(cli_sock);
        g_read_begin = g_read_end = 0;
    }
    return 0;
}

循环队列中加入了一个QUEUE_RESERVED_LEN长度,因为当队列首尾重叠的时候会产生歧义:队列是满还是空?为避免歧义,引入这个长度,规定首尾重叠时队列为空。

<==  index  ==>