Commit 32f68acc by shangshang.dai

Add 1:新增Socket类

parent bbce0280
#ifndef SOCKET_MODULE_H
#define SOCKET_MODULE_H
typedef struct {
unsigned int flag;
unsigned int ver;
unsigned int len;
}FMSOCKHEADER, *LPFMSOCKHEADER;
//socket 数据接收
//返回值 成功:接收长度
// 失败: -1
int socketRecvData(char * recvBuf, int bufSize, int socket_fd);
//通过 sockClient 发送数据
int socketSendData(const char * sendBuf, int socket_fd);
//socket server线程
void *FunSocketServer(void* lpParamter);
#include <string>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#define BUF_SIZE 1024*2
class TCPSocket
{
protected:
TCPSocket();
virtual ~TCPSocket();
bool create();
bool bind(unsigned short int port, const char *ip = NULL) const;
bool listen(int backlog = 1) const;
bool accept(TCPSocket &clientSocket) const;
bool connect(unsigned short int port, const char *ip) const;
bool reuseaddr() const;
public:
bool close();
int getfd() const{ return m_sockfd; }
//flag: true=SetNonBlock, false=SetBlock
bool setNonBlocking(bool flag) const;
protected:
int m_sockfd;
};
/** TCP Client **/
class TCPClient : public TCPSocket
{
private:
struct Packet
{
unsigned int msgLen; //数据部分的长度(网络字节序)
char text[BUF_SIZE]; //报文的数据部分
};
public:
TCPClient():m_bValid(false){}
~TCPClient(){}
/* 该函数会强制删除现有socket重新创建连接 */
bool doConnect(unsigned short port, const char *ip);
bool read(void *buf, size_t count);
bool write(const char *msg);
bool receive(std::string& message);
bool send(const std::string& message);
bool isValid(){ return m_bValid; }
private:
bool m_bValid;
};
/** TCP Server **/
class TCPServer : public TCPSocket
{
public:
TCPServer(){}
~TCPServer(){}
/* 该函数会强制删除现有socket重新创建监听 */
bool doListen(unsigned short int port, const char *ip = NULL, int backlog = SOMAXCONN);
bool accept(TCPSocket &clientSocket) const;
};
#endif
#include <iostream>
#include <fstream>
#include <fstream>
#include <pthread.h>
#include "JsonModule.h"
#include "SocketModule.h"
......@@ -12,9 +12,20 @@
INITIALIZE_EASYLOGGINGPP
std::string str_pos2ods_request;
std::string str_pos2ods_reply;
std::string str_ods2pos_push;
std::string str_ods2pos_reply;
std::string ods_ip;
int ods_listen_port;
int client_listen_port;
int pos_listen_port = 8009;
void logRolloutHandler(const char* filename, std::size_t size)
{
/// 备份日志
/// 备份日志
//std::string strLogPath = GetProcDir();
//strLogPath.append(filename);
......@@ -23,69 +34,183 @@ void logRolloutHandler(const char* filename, std::size_t size)
LOG(INFO)<<"备份日志:"<<ss.str().c_str();
system(ss.str().c_str());
}
void* listen_ods_func(void* arg)
{
TCPClient *client = (TCPClient*)arg;
while(true)
{
std::string msg;
// 判断是否成功连接ODS
if( !client->isValid() )
{
if( client->doConnect(ods_listen_port, ods_ip.c_str()) )
{
LOG(INFO) << "重连ODS成功";
}else
{
continue;
usleep(800);
}
}
if( client->receive(msg) != -1 )
{
// 判断是推送还是回复
std::string mark("push");
if( msg.compare(0, mark.size(), mark) == 0 )
{
// 为ODS的推送消息
TCPClient tmp_client;
if(tmp_client.doConnect(pos_listen_port, "127.0.0.1"))
{
if(tmp_client.send(msg))
{
std::string tmp_msg;
if(tmp_client.receive(tmp_msg))
{
str_pos2ods_reply = tmp_msg;
}else
{
str_pos2ods_reply = "获取POS返回值失败";
}
}else
{
LOG(INFO) << "转发失败: "<<msg;
str_pos2ods_reply = "推送给POS失败";
}
tmp_client.close();
}else
{
str_pos2ods_reply = "连接POS失败";
}
}else
{
// 为ODS的返回消息
str_ods2pos_reply = msg;
}
}else
{
LOG(INFO) << "ods连接失效,尝试重连。。。。。。";
}
}
}
void* listen_pos_func(void* arg)
{
TCPServer server;
if( server.doListen(client_listen_port) )
{
LOG(INFO) << "监听端口成功";
}
while(true)
{
std::string msg;
TCPClient connect;
if( server.accept(connect) )
{
if( connect.receive(msg) )
{
// POS请求数据
// 赋值给中间变量,等待其他线程发送给ODS
str_pos2ods_request = msg;
// 阻塞等待ODS返回
while(str_ods2pos_reply.empty())
{
usleep(200);
continue;
}
// 返回给POS
connect.send(str_ods2pos_reply);
str_ods2pos_reply.clear();
connect.close();
}else
{
LOG(INFO) << "接收POS推送消息失败";
}
}else
{
LOG(INFO) << "接受POS连接失败";
}
}
}
int main()
{
signal(SIGPIPE, SIG_IGN);
// 初始化日志
el::Loggers::addFlag(el::LoggingFlag::StrictLogFileSizeCheck);
std::string strBinPath = GetProcDir();
std::string strLogPath(strBinPath.data());
std::string strLogPath(strBinPath.data());
strLogPath.append("log.conf");
el::Configurations conf(strLogPath.data());
/// 设置全部logger的配置
/// 设置全部logger的配置
el::Loggers::reconfigureAllLoggers(conf);
/// 注册回调函数
/// 注册回调函数
el::Helpers::installPreRollOutCallback(logRolloutHandler);
LOG(INFO)<<"日志测试";
LOG(INFO)<<"--------------程序启动--------------";
//---------ini test-------------
std::string strIniPath(strBinPath.data());
// 读取配置文件信息
std::string strIniPath(strBinPath.data());
strIniPath.append("config.ini");
std::string ip = ZIni::readString("SYS","ip", "",strIniPath.c_str());
LOG(INFO)<<"读取配置文件ip:"<<ip.data();
//------------end---------------
//---------- json test----------
// std::string json = GetTestJson(100,"test data","123456789");
// LOG(INFO)<<"生成JSON" <<json.data();
ods_ip = ZIni::readString("ODS","ip", "", strIniPath.c_str());
ods_listen_port = ZIni::readInt("ODS", "listenPort", -1, strIniPath.c_str());
client_listen_port = ZIni::readInt("CLIENT", "listenPort", -1, strIniPath.c_str());
LOG(INFO) << "[ODS]服务器ip地址: " << ods_ip.data() << "-监听端口: " << ods_listen_port;
LOG(INFO) << "本地监听端口: " << client_listen_port;
// LOG(INFO)<<"JSON解析";
// parseJson(json.data());
JsonModule jsonMod;
orderObj obj;
productAttr product;
product.pro.source="123";
productSpec spec;
spec.name="只";
product.vecSpec.push_back(spec);
obj.vecProducts.push_back(product);
std::string orderInfo = jsonMod.convertToNewOrderJson(obj);
LOG(INFO)<<"订单信息转换成JSON:"<<orderInfo.data();
//------------end---------------
//---------- pthread test ---------
LOG(INFO)<<"启动SOCKET线程";
pthread_t printId;
int ret = pthread_create(&printId, NULL, FunSocketServer, NULL);
//---------- end ------------------
//---------- sqlite test-----------
SQLite sqlite;
sqlite.initSQLite();
sqlite.insert("insert into fmTest(fm_id, statusCode,msg,prompt,fm_open_id,total_amount,paid_total_amount,invoice_amount,incentives_amount)\
values('aabbcc',111,'abc',123,'cba',1,1,1,1)");
sqlite.query("select * from fmTest");
sqlite.update("update fmTest set statusCode=200 where fm_id='aabbcc'");
sqlite.query("select * from fmTest");
sqlite.remove("delete from fmTest where fm_id='aabbcc'");
sqlite.query("select * from fmTest");
sqlite.closeSQLite();
//-----------end------------------
char pStr[20];
std::cin>>pStr;
// 监听POS请求的线程
pthread_t listen_pos_id, listen_ods_id;
// 和ODS长连接通信
TCPClient ods_client;
if( ods_client.doConnect(ods_listen_port, ods_ip.c_str()) )
LOG(INFO) << "连接ODS成功";
/*创建 listen_pos 线程*/
if(pthread_create(&listen_pos_id,NULL,listen_pos_func,NULL))
LOG(INFO) << "创建listen_pos线程失败";
/*创建 listen_ods 线程*/
if(pthread_create(&listen_ods_id,NULL,listen_ods_func,&ods_client))
LOG(INFO) << "创建listen_pos线程失败";
while(true)
{
// 专门负责pos到ods的数据转发
if(!str_pos2ods_reply.empty())
{
// 将POS返回给ODS
if( ods_client.send(str_pos2ods_reply) )
{
str_pos2ods_reply.clear();
}else
{
}
}
if(!str_pos2ods_request.empty())
{
// 将POS的请求转发给ODS
if( ods_client.send(str_pos2ods_request))
{
str_pos2ods_request.clear();
}else
{
str_ods2pos_reply = "请求转发给ODS失败";
}
}
usleep(100);
}
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment