// ClientSocket.cpp : 实现文件
//

#include "stdafx.h"
#include "YAServer.h"
#include "ClientSocket.h"
#include "YAServerDlg.h"
#include "Functions/Functions.h"
#include "socketdef.h"
#include "socketdef.h"

// CClientSocket

CClientSocket::CClientSocket(CYAServerDlg* pDlg)
{
	m_pDlg = pDlg;
	m_bClosed = FALSE;
	bError = false;

	m_wReadLength = 0;
	m_wDataLength = 0;
	m_wCharacterWord = 0;
	reader_id = 0;
	m_ReceiveBuffer = (BYTE*)malloc(LENGTH_MSG_4K);
}

CClientSocket::~CClientSocket()
{
	free(m_ReceiveBuffer);
	//delete UserCallInfo;
}

void CClientSocket::Init()
{

}

void CClientSocket::Abort()
{

}

BOOL CClientSocket::SendData( WORD wCharacterWord, int wLength, BYTE* DataBuffer )
{
	BYTE SendBuffer[LENGTH_MSG_4K];
	WORD nlength = wLength + sizeof(WORD) + sizeof(WORD); //socket的数据长度 数据的长度(n) + 特征字(2) + 校验码（2）
	memset(SendBuffer, 0, LENGTH_MSG_4K);

	int nPos = 0;
	CFunctions::memcpyWord(SendBuffer, nlength, nPos);//长度
	nPos += sizeof(WORD);
	CFunctions::memcpyWord(SendBuffer, wCharacterWord, nPos);
	nPos += sizeof(WORD);
	memcpy(&SendBuffer[nPos], &DataBuffer[0], wLength);
	nPos += wLength;

	WORD wCrc = CFunctions::getCRC(&SendBuffer[sizeof(WORD)], wLength + sizeof(WORD)); // 数据长度 + 特征字
	CFunctions::memcpyWord(SendBuffer, wCrc, nPos);
	nPos += sizeof(WORD);

	int sRet = Send(SendBuffer, nPos);
	Sleep(20);

	if(sRet == SOCKET_ERROR)
	{
		return FALSE;
	}
	return TRUE;
}

void CClientSocket::OnSend(int nErrorCode)
{
	switch(nErrorCode)
	{
		case 0:
			break;
		case WSAENETDOWN:
			bError = true;			
			//m_pDlg->showerr();
			break;
		default:
			break;
	}
	CAsyncSocket::OnSend(nErrorCode);
}
void CClientSocket::OnReceive(int nErrorCode)
{
	if( nErrorCode != 0 )
	{
		bError = true;
		return;
	}
	bError = false;
	m_bClosed = FALSE;
	m_pDlg->receive_data(this);
	
	CAsyncSocket::OnReceive(nErrorCode);
}
void CClientSocket::OnConnect(int nErrorCode)
{
	if(0 != nErrorCode){
		m_pDlg->remove_socket(this);
	}
}
void CClientSocket::OnClose(int nErrorCode)
{
	bError = true;
	CAsyncSocket::OnClose(nErrorCode);
	//CString sMsg;
	//switch(nErrorCode)
	//{
	//	case WSAENETDOWN://套接字操作遇到一个不活动的网络
	//		sMsg="网络不可用：";
	//		break;
	//	case WSAECONNRESET://远程主机强制关闭
	//		sMsg="客户端强制关闭：";
	//		break;
	//	case WSAECONNABORTED://一个已建立的连接被你的主机上的软件终止，可能是因为一次数据传输超时或是协议错误。
	//		sMsg="关闭客户端：";
	//		break;
	//	case 0://正常退出
	//		sMsg="正常退出：";
	//		break;
	//	default:
	//		sMsg="退出：";
	//		break;
	//}
	if(m_bClosed){
		return;
	}
	m_pDlg->remove_socket(this);
	m_bClosed = TRUE;
	ShutDown();
	//delete this;
}

IMPLEMENT_DYNAMIC(CClientSocket, CAsyncSocket)