Click here to Skip to main content
15,896,118 members
Articles / Desktop Programming / MFC

How to create a chat client using a set of communication classes

,
Rate me:
Please Sign up or sign in to vote.
3.71/5 (6 votes)
25 Aug 2003Apache4 min read 79.6K   2.5K   37  
A pair of classes (no mfc) that can be used for tcp/ip _and_ serial communication.
#include "StdAfx.h"
#include "dtsocketbase.h"

Datatal::DtSocketBase::DtSocketBase(void)
{
	m_bReconnect = false;

	//Create events
	m_hNewDataEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	m_nBufferPos = 0;
	m_lOutBuffers.pFirst = NULL;
	m_lOutBuffers.pLast = NULL;
}

Datatal::DtSocketBase::~DtSocketBase(void)
{
	Disconnect(true);
	CloseHandle(m_hNewDataEvent);
}

bool Datatal::DtSocketBase::Disconnect(bool bStopThread /* = false */)
{
	SetState(DTSS_DISCONNECTED);

	m_CritWrite.Lock();
	while (m_lOutBuffers.pFirst)
		m_lOutBuffers.RemoveFirst();
	m_CritWrite.Unlock();

	if (bStopThread)
	{
		SetReconnect(false);
		StopThread();
	}

	return true;
}

void Datatal::DtSocketBase::WriteLog(int nImportance, const char* pszGroup, LPCTSTR lpszFormat, ...)
{
	char		szFormattedString[1124];
	va_list		argptr;

	//Initialize 
	memset(szFormattedString, 0, sizeof(szFormattedString));

	//Format Data
	va_start(argptr,lpszFormat);
	vsprintf(szFormattedString,lpszFormat,argptr);
	va_end(argptr);

	HandleWriteLog(nImportance, pszGroup, szFormattedString);
}


bool Datatal::DtSocketBase::Send(char* szBuffer, size_t nBufSize)
{

	//Lock outbuffer
	m_CritWrite.Lock();
	WriteLog(Datatal::LP_NORMAL, "Send", "Appending new buffer, size: %d", nBufSize);
	m_lOutBuffers.Append(szBuffer, nBufSize);
	m_CritWrite.Unlock();

	//Signal thread that new data exist.
	if (!SetEvent(m_hNewDataEvent))
		WriteLog(Datatal::LP_HIGH, "Send", "Set hNewDataEvent Failed!");

	return true;
}

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, along with any associated source code and files, is licensed under The Apache License, Version 2.0


Written By
Founder 1TCompany AB
Sweden Sweden

Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions