C++自定义封装自定义封装socket操作业务类完整实例操作业务类完整实例
本文实例讲述了C++自定义封装socket操作业务类。分享给大家供大家参考,具体如下:
Linux下C++封装socket操作的工具类(自己实现)
socketconnector.h
#ifndef SOCKETCONNECTOR_H
#define SOCKETCONNECTOR_H
#include "global.h"
using namespace std;
class SocketConnector
{
public:
typedef enum {
ENormal,
EOther,
} SocketState;
public:
static SocketConnector * getInstance();
inline SocketState state(){ return m_state; }
inline void setState(SocketState _state){ m_state = _state; }
inline bool isConnected() { return m_isConnected; }
inline void setConnected(bool state) { m_isConnected = state; }
void start();
inline void setServerIP(string ip){ m_server_ip = ip;}
inline void setServerPort(int port){ m_server_port = port; }
int connect_sockfd();
int onSendMessage(string & message);
private:
SocketConnector();
void onConnectToServer(string & ip,int port);
static void * onReportMessage(void * p);
static void * onReadMessage(void * p);
static void * onWriteMessage(void * p);
private:
SocketState m_state;
bool m_isConnected;
int m_sockFd;
string m_server_ip;
int m_server_port;
pthread_t m_report_tid;
pthread_t m_read_tid;
pthread_t m_write_tid;
};
#endif // SOCKETCONNECTOR_H
socketconnector.cpp
#include "global.h"
#include "socketconnector.h"
#include "cmessagecenter.h"
#include "cmip_requestparser.h"
#include "csettings.h"
#include "datadef.h"
#include "cstringutils.h"
using namespace std;
static SocketConnector * g_instance = NULL;
/**************************************************************************************************
* Single Instance.
***************************************************************************************************/
SocketConnector * SocketConnector::getInstance()
{
if (g_instance == NULL)
{
g_instance = new SocketConnector();
}
return g_instance;
}
/**************************************************************************************************
* Consturoctor
***************************************************************************************************/
SocketConnector::SocketConnector()
{
m_isConnected = false;
m_state = ENormal;