/*************************************************************
/* Copyright (C), 2014-2020, lyfz. Co., Ltd.
/* 文件名:		IClientImpl.h  
/* 作者:		Jeff.w			 
/* 创建日期:	2014-08-07
/* 版本号:		V1.0
/* 描述:		核心层底,客户端与服务端通信接口
/* 其它:  
/* 主要类模块: 
/* 历史修改记录: 
/*		作者           时间              版本           描述
/*	    Jeff.w         14/08/07          1.0	      创建这个模块
***************************************************************/

#pragma once

#include <afxwin.h>
#include <atlbase.h>
//#pragma warning(push)
//#pragma warning(disable:4995)
//#pragma warning(pop)
#include "CritSection.h"
#include "SocketHandle.h"
#include "SocketClientImpl.h"


#include "Global.h"

// 宏定义:计算数据包总长度;
#define CALCDATALEN(x) (x+sizeof(STProtocolheader)+sizeof(STProtocoltail))
//const int TCPCLIENTNUM = 10;

class IClientImpl :	public ISocketClientHandler
{
	typedef SocketClientImpl<ISocketClientHandler> CSocketClient;
	friend CSocketClient;

public:
	IClientImpl();
	~IClientImpl();
	
	//static IClientImpl* GetInstancePtr( int iTCPIndex );
	void StartReConnectSrvThread();
	static DWORD WINAPI ReConnectSrvThread(LPVOID pInstance);

protected:
	virtual void OnThreadBegin(CSocketHandle* pSH);
	virtual void OnThreadExit(CSocketHandle* pSH);
	virtual void OnDataReceived(CSocketHandle* pSH, const BYTE* pbData, DWORD dwCount, const SockAddrIn& addr);
	virtual void OnConnectionDropped(CSocketHandle* pSH);
	virtual void OnConnectionError(CSocketHandle* pSH, DWORD dwError);

protected:
	CString m_strPort;
	int m_nMode;		// IPV4 或 IPV6
	int m_nSockType;	// UDP 或 TCP

	// 线程句柄;
	HANDLE m_hReConnectSrvThreadHandle;

	// 线程退出句柄;
	HANDLE m_hRunObject;

	//static IClientImpl *m_pTcpClient[TCPCLIENTNUM];

	void _cdecl AppendText(LPCTSTR lpszFormat, ...);
	void GetAddress(const SockAddrIn& addrIn, CString& rString) const;
	bool GetDestination(SockAddrIn& addrIn) const;
	bool SetupMCAST();

	// Jeff.最新研究出来的处理方案;
	// 对异常包需要计数处理,当1分钟内出现多少异常包时,需要重启服务函数;
	//unsigned int VerityIntegrityPacket(IN void *pIntegrityPacket,unsigned int nPacketSize);
	void ToprocessRecivebuf(IN CSocketHandle *sockHandle, IN const BYTE* pReceivebuf, IN DWORD dwReceiveSize);
	int  OnIntegrityPacket(IN CSocketHandle *sockHandle, IN void *pIntegrityPacket);

public:
	BOOL m_bStopbeat;	// 是否心跳包;
	BOOL m_bSocket;
	CSocketClient m_SocketClient;
	BOOL Initialize();
	BOOL ConnectServer(LPCTSTR strAddr, LPCTSTR strPort);
	void DisConnectServer();
	void SendMsg(void *pMsg,const int nLen);
	void SendFile(LPCTSTR lpzFileName,LPCTSTR strPort);
};
