Click here to Skip to main content
15,891,513 members
Articles / Desktop Programming / MFC

Barry's Chat System

Rate me:
Please Sign up or sign in to vote.
4.91/5 (8 votes)
24 Nov 20025 min read 140.5K   7.5K   57  
Barry's Chat System
// ChatClientDoc.cpp : implementation of the CChatClientDoc class
//
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) 1992-1998 Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.

// ChatClientDoc.cpp : implementation of the CChatClientDoc class
//

#include "stdafx.h"
#include "ChatClient.h"

#include "ChatClientDoc.h"

#include "LogonDlg.h"

#include "LeftView.h"
#include "MessageView.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define JOINING_CHAT          1
#define LEAVING_CHAT          2
#define SENDING_CHATTERS_LIST 3
#define SENDING_NICKNAME      4
#define NORMAL_MESSAGE        5
#define DUPLICATE_NICKNAME    6


/////////////////////////////////////////////////////////////////////////////
// CChatClientDoc

IMPLEMENT_DYNCREATE(CChatClientDoc, CDocument)

BEGIN_MESSAGE_MAP(CChatClientDoc, CDocument)
	//{{AFX_MSG_MAP(CChatClientDoc)
	ON_COMMAND(ID_CONNECT, OnConnect)
	ON_UPDATE_COMMAND_UI(ID_CONNECT, OnUpdateConnect)
	ON_UPDATE_COMMAND_UI(ID_DISCONNECT, OnUpdateDisconnect)
	ON_COMMAND(ID_DISCONNECT, OnDisconnect)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CChatClientDoc construction/destruction

CChatClientDoc::CChatClientDoc()
{
	// TODO: add one-time construction code here
	bIsConnected = FALSE;
	m_pSocket = NULL;
	m_pFile = NULL;
	m_pArchiveOut = NULL;
	m_pArchiveIn = NULL;
}

CChatClientDoc::~CChatClientDoc()
{
}

BOOL CChatClientDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument())
		return FALSE;

	// TODO: add reinitialization code here
	// (SDI documents will reuse this document)


	return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CChatClientDoc serialization

void CChatClientDoc::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		for(POSITION pos=GetFirstViewPosition();pos!=NULL;)
		{
			CView* pView = GetNextView(pos);
			CMessageView* pChatView = DYNAMIC_DOWNCAST(CMessageView, pView);

			if (pChatView != NULL)
				pChatView->Serialize(ar);

		}
	}
}

/////////////////////////////////////////////////////////////////////////////
// CChatClientDoc diagnostics

#ifdef _DEBUG
void CChatClientDoc::AssertValid() const
{
	CDocument::AssertValid();
}

void CChatClientDoc::Dump(CDumpContext& dc) const
{
	CDocument::Dump(dc);
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CChatClientDoc commands


void CChatClientDoc::DeleteContents()
{

	if ((m_pSocket != NULL) && (m_pFile != NULL) && (m_pArchiveOut != NULL))
	{
		CMsg msg;
		CString strTemp;

		if (strTemp.LoadString(IDS_DISCONNECT))
		{
			SendMsg(m_strHandle, LEAVING_CHAT, false);

			msg.code = NORMAL_MESSAGE;
			msg.m_bClose = TRUE;
			msg.m_strText = m_strHandle + strTemp;
			msg.Serialize(*m_pArchiveOut);
			m_pArchiveOut->Flush();
		}
	}

	delete m_pArchiveOut;
	m_pArchiveOut = NULL;
	delete m_pArchiveIn;
	m_pArchiveIn = NULL;
	delete m_pFile;
	m_pFile = NULL;

	if (m_pSocket != NULL)
	{
		BYTE Buffer[50];
		m_pSocket->ShutDown();

		while(m_pSocket->Receive(Buffer,50) > 0);
	}

	delete m_pSocket;
	m_pSocket = NULL;

	for(POSITION pos=GetFirstViewPosition();pos!=NULL;)
	{
		CView* pView = GetNextView(pos);

		if (pView->IsKindOf(RUNTIME_CLASS(CMessageView)))
		{
			CMessageView* pChatView = (CMessageView*)pView;
			pChatView->GetEditCtrl().SetWindowText(_T(""));
		}
		if (pView->IsKindOf(RUNTIME_CLASS(CLeftView)))
		{
			CLeftView* pLeftView = (CLeftView*)pView;
			pLeftView->ClearChattersList();
		}
	}

	CDocument::DeleteContents();
}


BOOL CChatClientDoc::ConnectSocket(LPCTSTR lpszHandle, LPCTSTR lpszAddress, UINT nPort)
{
	m_strHandle = lpszHandle;

	m_pSocket = new CChatSocket(this);

	if (!m_pSocket->Create())
	{
		delete m_pSocket;
		m_pSocket = NULL;
		AfxMessageBox(IDS_CREATEFAILED);
		return FALSE;
	}

	while (!m_pSocket->Connect(lpszAddress, nPort + 1500)) // 700
	{
		if (AfxMessageBox(IDS_RETRYCONNECT,MB_YESNO) == IDNO)
		{
			delete m_pSocket;
			m_pSocket = NULL;
			return FALSE;
		}
	}

	m_pFile = new CSocketFile(m_pSocket);
	m_pArchiveIn = new CArchive(m_pFile,CArchive::load);
	m_pArchiveOut = new CArchive(m_pFile,CArchive::store);

	
	SendMsg(m_strHandle, SENDING_NICKNAME, false);
	
	CString strTemp;
	if (strTemp.LoadString(IDS_CONNECT))
		SendMsg(strTemp, NORMAL_MESSAGE, true);

	return TRUE;
}

void CChatClientDoc::ProcessPendingRead()
{
	do
	{
		ReceiveMsg();
		if (m_pSocket == NULL)
			return;
	}
	while(!m_pArchiveIn->IsBufferEmpty());
}

void CChatClientDoc::SendMsg(CString& strText, UINT mCode, BOOL bSendHandle)
{
	if (m_pArchiveOut != NULL)
	{
		CMsg msg;

		msg.code = mCode;

		msg.m_strText = (bSendHandle ? m_strHandle + _T(": ") + strText : strText);

		TRY
		{
			msg.Serialize(*m_pArchiveOut);
			m_pArchiveOut->Flush();
		}
		CATCH(CFileException, e)
		{
			m_pArchiveOut->Abort();
			delete m_pArchiveOut;
			m_pArchiveOut = NULL;

			CString strTemp;
			if (strTemp.LoadString(IDS_SERVERRESET))
				DisplayMsg(strTemp);
		}
		END_CATCH
	}
}

void CChatClientDoc::ReceiveMsg()
{
	CMsg msg;

	TRY
	{
		msg.Serialize(*m_pArchiveIn);

		if(msg.code == SENDING_CHATTERS_LIST)
		{
			UpdateChattersList(&msg);
		}
		if(msg.code == DUPLICATE_NICKNAME)
		{
			AfxMessageBox(msg.m_strText);
			msg.m_bClose = TRUE;
			OnDisconnect();
		}
		while(!msg.m_msgList.IsEmpty())
		{
			CString temp = msg.m_msgList.RemoveHead();
			DisplayMsg(temp);
		}

	}
	CATCH(CFileException, e)
	{
		msg.m_bClose = TRUE;
		m_pArchiveOut->Abort();

		CString strTemp;
		if (strTemp.LoadString(IDS_SERVERRESET))
			DisplayMsg(strTemp);
		if (strTemp.LoadString(IDS_CONNECTIONCLOSED))
			DisplayMsg(strTemp);
	}
	END_CATCH

	if (msg.m_bClose)
	{
		delete m_pArchiveIn;
		m_pArchiveIn = NULL;
		delete m_pArchiveOut;
		m_pArchiveOut = NULL;
		delete m_pFile;
		m_pFile = NULL;
		delete m_pSocket;
		m_pSocket = NULL;
	}
}

void CChatClientDoc::DisplayMsg(LPCTSTR lpszText)
{

	for(POSITION pos=GetFirstViewPosition();pos!=NULL;)
	{
		CView* pView = GetNextView(pos);
		CMessageView* pChatView = DYNAMIC_DOWNCAST(CMessageView, pView);

		if (pChatView != NULL)
			pChatView->Message(lpszText);
	}
}

void CChatClientDoc::UpdateChattersList(CMsg* pMsg)
{

	CLeftView* pLeftView;

	for(POSITION pos=GetFirstViewPosition();pos!=NULL;)
	{
		CView* pView = GetNextView(pos);
		pLeftView = DYNAMIC_DOWNCAST(CLeftView, pView);

		if (pLeftView != NULL)
			pLeftView->ClearChattersList();
	}
	
	CString strTemp = (pMsg->m_strText == "" ? pMsg->m_msgList.RemoveHead() : pMsg->m_strText);
	do
	{
		CString sName = strTemp.Left(strTemp.Find(":",0));
		pLeftView->AddToChattersList(sName);
		strTemp = strTemp.Mid(strTemp.Find(":" , 0)+1);
	}while(strTemp.Find(":",0) != -1);

}

void CChatClientDoc::OnConnect() 
{
	CLogonDlg dlg;
	dlg.m_NickName = _T("Barry");
	dlg.m_Port = 0;
	dlg.m_Server = _T("127.0.0.1");

	while(TRUE)
	{
		if (IDOK != dlg.DoModal())
			return;

		if (ConnectSocket(dlg.m_NickName, dlg.m_Server, dlg.m_Port))
		{
			bIsConnected = TRUE;
			return;
		}

		if (AfxMessageBox(IDS_CHANGEADDRESS,MB_YESNO) == IDNO)
			return ;
	}
		
}

void CChatClientDoc::OnUpdateConnect(CCmdUI* pCmdUI) 
{
	pCmdUI->Enable(!bIsConnected);
}

void CChatClientDoc::OnUpdateDisconnect(CCmdUI* pCmdUI) 
{
	pCmdUI->Enable(bIsConnected);	
}

void CChatClientDoc::OnDisconnect() 
{
	// TODO: Add your command handler code here
	DeleteContents();
	bIsConnected = FALSE;
}

void CChatClientDoc::ClearMessages()
{

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
India India
Nothing to boast about

Comments and Discussions