clientsocket.cpp
来自「基于winsock的聊天程序」· C++ 代码 · 共 133 行
CPP
133 行
// CLientSocket.cpp : implementation file
//
#include "stdafx.h"
#include "ChatServer.h"
#include "CLientSocket.h"
#include "ChatServerDoc.h"
#include "Msg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CCLientSocket
CClientSocket::CClientSocket(CChatServerDoc* pDoc)
{
m_pDoc = pDoc;
m_nMsgCount = 0;
m_pFile = NULL;
m_pArchiveIn = NULL;
m_pArchiveOut = NULL;
needdel=false;
}
/////////////////////////////////////////////////////////////////////////////
// CClientSocket Operations
void CClientSocket::Init()
{
m_pFile = new CSocketFile(this);
m_pArchiveIn = new CArchive(m_pFile,CArchive::load);
m_pArchiveOut = new CArchive(m_pFile,CArchive::store);
}
void CClientSocket::Abort()
{
if (m_pArchiveOut != NULL){
m_pArchiveOut->Abort();
delete m_pArchiveOut;
m_pArchiveOut = NULL;
}
}
void CClientSocket::SendMsg(CMsg* pMsg)
{
if (m_pArchiveOut != NULL){
pMsg->Serialize(*m_pArchiveOut);
m_pArchiveOut->Flush();
}
}
void CClientSocket::ReceiveMsg(CMsg* pMsg)
{
pMsg->Serialize(*m_pArchiveIn);
}
/////////////////////////////////////////////////////////////////////////////
// CClientSocket Overridable callbacks
void CClientSocket::OnReceive(int nErrorCode)
{
CSocket::OnReceive(nErrorCode);
m_pDoc->ProcessPendingRead(this);
}
BOOL CClientSocket::HasConnectionDropped( void )
{
BOOL bConnDropped = FALSE;
INT iRet = 0;
BOOL bOK = TRUE;
struct timeval timeout = { 0, 0 };
fd_set readSocketSet;
FD_ZERO( &readSocketSet );
FD_SET( m_hSocket, &readSocketSet );
iRet = ::select( 0, &readSocketSet, NULL, NULL, &timeout );
bOK = (iRet > 0);
if(bOK){
bOK = FD_ISSET( m_hSocket, &readSocketSet );
}
if( bOK ){
CHAR szBuffer[1] = "";
iRet = ::recv( m_hSocket, szBuffer, 1, MSG_PEEK );
bOK = ( iRet > 0 );
if( !bOK ){
INT iError = ::WSAGetLastError();
bConnDropped = ( ( iError == WSAENETRESET ) ||
( iError == WSAECONNABORTED ) ||
( iError == WSAECONNRESET ) ||
( iError == WSAEINVAL ) ||
( iRet == 0 ) ); //Graceful disconnect from other side.
}
}
return( bConnDropped );
}
/////////////////////////////////////////////////////////////////////////////
// CSocket Implementation
CClientSocket::~CClientSocket()
{
if (m_pArchiveOut != NULL)
delete m_pArchiveOut;
if (m_pArchiveIn != NULL)
delete m_pArchiveIn;
if (m_pFile != NULL)
delete m_pFile;
}
#ifdef _DEBUG
void CClientSocket::AssertValid() const
{
CSocket::AssertValid();
}
void CClientSocket::Dump(CDumpContext& dc) const
{
CSocket::Dump(dc);
}
#endif //_DEBUG
IMPLEMENT_DYNAMIC(CClientSocket, CSocket)
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?