| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- #pragma once
- #include <websocketpp/config/asio_no_tls_client.hpp>
- #include <websocketpp/client.hpp>
- #include <boost/asio/steady_timer.hpp >
- #include <iostream>
- #include <atomic>
- #include <afx.h>
- #include "NetInterface.h"
- #include "Scheduler.h"
- using websocketpp::lib::placeholders::_1;
- using websocketpp::lib::placeholders::_2;
- class CPduEntity;
- class CNetClient:public CNetInterface
- {
- typedef websocketpp::client<websocketpp::config::asio_client> client;
- typedef websocketpp::config::asio_client::message_type::ptr message_ptr;
- typedef CNetClient this_type;
- public:
- CNetClient();
- virtual ~CNetClient();
- // 接口函数
- virtual void setLinkStateChanged(LinkStateChangedFuncCB funcCB) ; // PDU连接状态变化事件处理
- virtual void setRecvCommand(RecvComdFuncCB funcCB) ; // PDU命令到达事件处理
- virtual bool CreatePduClient(CString a_strFarIp,
- int a_nFarPort,
- PDU_DEV_TYPE a_nLocalType,
- int a_nLocalId,
- bool IsAutoReconnect);
- virtual bool ClosePduClient(PDU_DEV_TYPE a_nFarType,
- int a_nFarId); // 关闭PDU通讯客户端
- virtual bool Send(CPduEntity* a_pCmd, PDU_DEV_TYPE a_nDestType = PDU_DEV_TYPE_UNKNOWN, int a_nDestId = 0);
- private:
- void SetLinkContent(PDU_LINK_STATE a_nLinkInfo);
- void SetTimerListen(); // 开启心跳定时
- void KillTimerListen(); // 关闭心跳定时
- void SetTimerConn(); // 开启自动连接
- void KillTimerConn(); // 关闭自动连接
- private:
- void on_open(websocketpp::connection_hdl hdl);
- void on_fail(websocketpp::connection_hdl hdl);
- void on_close(websocketpp::connection_hdl hdl);
- void on_message(websocketpp::connection_hdl hdl, message_ptr msg);
- int init();
- bool ConnectToServer(const CString& a_strFarIp,
- int a_nFarPort,
- PDU_DEV_TYPE a_nLocalType,
- int a_nLocalId); // 连接到SERVER端
- bool connect();
- void close();
- void terminate();
- public:
- static CNetClient* getInstance() { return &instance; }
- private:
- bool __SendBuf(unsigned char a_szBuf[], std::uint32_t a_nBufLen);
- void onTime(const std::int32_t& TimerId);
- inline std::string devTypeToStr(PDU_DEV_TYPE devType);
- private:
- boost::asio::io_service ios;
- client c;
- websocketpp::lib::shared_ptr<websocketpp::lib::thread> thread_;
- websocketpp::lib::shared_ptr<websocketpp::lib::thread> thread1_;
- websocketpp::connection_hdl hdl_;
- std::string uri;
- std::unique_ptr<CScheduler> m_pSchedulerHeart; // 心跳定时器
- std::unique_ptr<CScheduler> m_pSchedulerAutoConn; // 心跳定时器
- // 属性
- PDU_DEV_TYPE m_DevType; // 本端设备类型
- int m_DevId; // 本端设备ID
- bool m_IsAutoReconnect; // 是否自动重连
- std::atomic_bool m_IsConnSuccess; // 连接是否成功
- RecvComdFuncCB m_RecvComdFuncCB; // 消息回调函数
- LinkStateChangedFuncCB m_LinkStateChangedFuncCB; // 连接状态变化回调函数
- static CNetClient instance;
- };
- //需要重复打开关闭连接时,只调用一次init_asio()函数,
- //然后调用start_perpetual()将endpoint设置为永久的,
- //不会在连接断开时自动退出。需要结束循环,调用stop_perpetual()
|