pans
2017-08-30 71c92f101b6c8b4a678a8c3cfe2d8edbf488efa4
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
#ifndef __PUBLIC_TCPCOMM_H__
#define __PUBLIC_TCPCOMM_H__
#define UNIX_PLATFORM
#ifdef UNIX_PLATFORM
//#include "wintypes.h"
 
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <termio.h>
#include <string.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
 
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/select.h>
//#include <prototypes.h>
#include <sys/times.h>
 
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#define    _stat    stat
 
#define    TCP_CLOSE(a)    close(a)
#define TCP_DELAY(a)    sleep(a*1000)
 
#define SOCKET_ERROR    (-1)
 
#else
#include <winsock2.h>
#include <process.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
 
#define TCP_CLOSE(a)    closesocket(a)
#define TCP_DELAY(a)    Sleep(a)
 
#endif
 
enum enTcpCommConst {
    TCC_INVALIDVALUE = -1, TCC_MINFILETRANSBLK = 512, TCC_DFTFILETRANSBLK = 64 * 1024
};
#define SOCKET_TIMEOUT        500
 
#define TCP_ERROR_CONNECT    -1001
#define TCP_ERROR_SEND        -1002
#define TCP_ERROR_RECV        -1003
 
// Simple tcp communication class.
class tcpComm {
public:
    tcpComm();
    virtual ~tcpComm();
 
    // 创建环境
    bool Create(long nCommTimeOut, long nRefreshMode = 0, long nTimeFailMode = 0);
    // 创建服务器
    int CreateNetServer(unsigned short nServicePort);
    // 服务器侦听
    int WaitingNetServer();
    // 连接服务器
    int ConnectNetServer(const char * pSerIp, unsigned short nSerPort);
    // 非阻塞模式
    int EnableNoBlockMode(int flag);
    // 发送数据块
    int SendData(unsigned char *send_buf, long nSize);
    // 发送文件
    int SendFile(char *filename);
    // 接收数据块
    int RecvData(unsigned char *recv_buf, long nSize);
    // 接收文件
    int RecvFile(char *filename, long nSize);
    // 关闭连接
    int CloseComm();
    // 设置操时时间
    void SetCommTimeOut(int nCommTimeOut) {
        m_nCommTimeOut = nCommTimeOut;
    }
 
private:
    int m_sockfd;
    long m_nCommTimeOut;        // 通信超时
    long m_nRefreshMode;        // 累积记时或刷新记时模式
    long m_nTimeFailMode;    // 通信超时是否作为通信中断
};
 
#endif //__PUBLIC_TCPCOMM_H__