Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
135 lines (121 sloc) 3.16 KB
#ifndef __TCPSOCKET_H__
#define __TCPSOCKET_H__
#include "base.h"
enum SocketTypes {
COMM_SOCKET = 0,
LISTEN_SOCKET
};
enum ConnectStatus {
CLOSED = 0,
OPENED,
CONNECTED,
ERROR
};
enum RecvErrors {
ERR_RECV_NOSOCK = -11,
ERR_RECV_NOAPPBUFF = -12,
ERR_RECV_REMOTE = -13,
ERR_RECV_FAILED = -14
};
enum SendErrors {
ERR_SEND_NOSOCK = -11,
ERR_SEND_NOTCPBUFF = -12,
ERR_SEND_FAILED = -13
};
class TCPSocket {
public:
TCPSocket(unsigned int max_recv_buf_len = MAX_RECV_BUF_LEN,
unsigned int max_post_buf_len = MAX_POST_BUF_LEN);
virtual~TCPSocket();
TCPSocket& operator=(const TCPSocket& t);
int Init(unsigned int max_recv_buf_len = MAX_RECV_BUF_LEN,
unsigned int max_post_buf_len = MAX_POST_BUF_LEN);
int CreateServer(unsigned short port, char* ip=0);
int CreateClient(char* ip=0);
int SetNonBlock();
int SetReuseAddr();
int Close();
int Accept(TCPSocket& comm_socket);
int ConnectTo(char* ip, unsigned short port);
int RecvBytes();
int GetOneCode(unsigned int& code_len, unsigned char* code);
int SendReservedBytes();
int GetReservedBytes();
int SendOneCode(unsigned int code_len,
unsigned char* code, bool is_reserve=true);
int GetTCPSendBufLen();
int GetTCPRecvBufLen();
int SetTCPSendBufLen(int len);
int SetTCPRecvBufLen(int len);
int get_socket() const {
return socket_;
}
SocketTypes get_socket_type() const {
return socket_type_;
}
ConnectStatus get_connect_status() const {
return connect_status_;
}
unsigned short get_port() const {
return port_;
}
void get_ip(char ip[IP_LEN]) const {
memcpy(ip, ip_, IP_LEN);
}
int get_recv_begin() const {
return recv_begin_;
}
int get_recv_end() const {
return recv_end_;
}
int get_post_begin() const {
return post_begin_;
}
int get_post_end() const {
return post_end_;
}
unsigned char* get_recv_buf() const {
return recv_buf_;
}
unsigned char* get_post_buf() const {
return post_buf_;
}
unsigned int get_max_recv_buf_len() const {
return max_recv_buf_len_;
}
unsigned int get_max_post_buf_len() const {
return max_post_buf_len_;
}
sockaddr_in get_addr() const {
return addr_;
}
void set_addr(sockaddr_in addr) {
addr_ = addr;
}
void set_socket(int socket) {
socket_ = socket;
}
void set_socket_type(SocketTypes type) {
socket_type_ = type;
}
void set_connect_status(ConnectStatus status) {
connect_status_ = status;
}
private:
int SendBytes();
int ReserveBytes(unsigned int bytes_cnt, unsigned char* bytes);
private:
int socket_;
sockaddr_in addr_;
SocketTypes socket_type_;
ConnectStatus connect_status_;
unsigned short port_;
char ip_[IP_LEN];
int recv_begin_, recv_end_;
int post_begin_, post_end_;
unsigned char* recv_buf_;
unsigned char* post_buf_;
unsigned int max_recv_buf_len_;
unsigned int max_post_buf_len_;
};
#endif /* __TCPSOCKET_H__ */