Creating a Chat System
Environment: VC6 SP3, VC7, Win98, Win2000, WinXP
Introduction
This article demonstrates the technique of creating a Chat System. The article contains a Chat Server and a Chat Client; each perform different tasks and cannot be used interchangeably. Both client and server use Windows Sockets for the purpose of connecting and sending lines of text between themselves; you can use the Server and Client either on your machine or over a private Lan or network to chat.
Note: I do not have access to either a Lan or network, hence this software was only tested in a "Local Loop" on my machine. Anyone testing the software over a network can please send the the test results through e-mail to barretto_vn@mail.com.
How to Use the Chat Server and Chat Client
Preparing to Use ChatServer and Client
- Download the ChatServer and ChatClient Source code.
- Unzip ChatServer and ChatClient Source code.
- Start Visual Studio.
- Build the ChatServer and ChatClient executeables.
- Exit Visual Studio.
To use the ChatServer and ChatClient on your machine in what is know as a "Local Loop," do the following:
Starting ChatServer
- Start ChatServer (the executeable is in the ChatServer\Debug folder).
- Keep the Port Number as 0 and click OK. (Note: If you change the Port Number, the same number must be used when connecting through ChatClient.)
- The Port Number can be between 0 to 1499. (This is useful in cases where the Port Number is in use by another application on the Server System.)
Note: Even though the Port Number input is 0, it is in reality 1500 + x (x stands for the Port Number you input—0 in this case).
Starting ChatClient
- Start ChatClient (the executeable is in the ChatClient\Debug folder).
- From the menu, select Connection->Connect (or click the Connect button).
- A Logon Form will be displayed.
- In the Server box, type 127.0.0.1.
- In the Nickname box, type any name (should be different for each invocation of ChatClient).
- In the Port Number box, type 0 (remember that we had started the Chat Server with 0 as the Port Number).
- Click OK.
Repeat Steps 1 thru 7 above to start another ChatClient but with a different Nickname. You can start as many ChatClients as you want, restricted only by available memory. Chat to your heart's content—with yourself, of course.
To Use ChatServer and ChatClient on a network, do the following; carry out the steps in "Preparing to use ChatServer and ChatClient," above
- Copy the ChatServer executeable on a Server system.
- Copy the ChatClient executeables on machines from where you want users to chat.
- Start ChatServer on the Server system; refer to the "Starting ChatServer" section above.
- Start ChatClient on the machines where the ChatClient was copied; refer to the "Starting ChatClient" section above, but remember that in the Server Box on the Logon form you have to type the name or IP Address of the Server system on which the ChatServer is running (not 127.0.0.1) and Port Number, as applicable.
Caution
If you copy the ChatServer and ChatClient executeables on machines that do not have Visual Studio set up, the executeables may not run because MFC is not installed by default on the Windows operating system.
The Installable versions of ChatServer and ChatClient are available for download in the Download section; you can install both on any machine running Windows 9x / Windows 2000 / Windows XP because the Installable versions have MFC included.
I may not upload the Installable versions at the present because of their huge size (1.2Mb each); and, to be very frank, I cannot afford it at the present time. Maybe I will over a period of time, if there is a demand for them.
What's Missing
- No Coloured Text for chatting
- No Variable Fonts for chatting
- Single Chat Room
- No Threads Used in the Source
Maybe, in a later version, the above could be incorporated; they are presently under testing.
Note for Developers
The most important coding for both the Server and Client is in the CChatServerDoc and CChatClientDoc classes. You would do well to concentrate on these two classes.
A CObject class named CMsg is used in both the Server and Client to send and receive messages back and forth; the messages are then unassembled by the receiver (Server or Client). The CMsg class has the following members:
- Code (to indicate the type of message)
- m_strText (message text)
- m_bClose (sent when the Client is disconnecting or shutting down
Following is a list of codes sent by both Server and Client (you can have your own codes as the need arises):
#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
How It Works
After you start the Server by inputting the Port Number and clicking OK, a Socket is created for listening for incoming connect requests using the following code in the member function OnNewDocument():
m_pSocket = new CListeningSocket(this);
if (m_pSocket->Create(Dialog.m_nPort+1500))
{
if (m_pSocket->Listen())
return TRUE;
}
When a new connect request is received from a client, the member function OnAccept in the CListeningSocket class is notified by the system. OnAccept then calls the ProcessPendingAccept function in the CChatServerDoc class, as show below:
void CListeningSocket::OnAccept(int nErrorCode)
{
CSocket::OnAccept(nErrorCode);
m_pDoc->ProcessPendingAccept();
}
In the ProcessPendingAccept function, a new Socket (CClientSocket) is created for the new client and the created Socket is added to the Pointer List CPtrList, which is a kind of array. We use the pointer list all through the program to retreive the Socket for sending or receving messages. The system then reads the incoming message in the member function OnReceive in the CClientSocket, which in turn calls ProcessPendingRead, sending to it the Client Socket which sent the message, as shown below.
void CClientSocket::OnReceive(int nErrorCode)
{
CSocket::OnReceive(nErrorCode);
m_pDoc->ProcessPendingRead(this);
}
Inside ProcessPendingRead, the CMsg object sent by the client is unassembled and, based on the code of the message, action is taken as appropriate.
When a Client Disconnects or Exits by selecting File->Exit, a message is sent to the Server with m_bClose set to TRUE. The Server receives the message and closes the Client Socket as show below:
void CChatServerDoc::CloseSocket(CClientSocket* pSocket)
{
// Close the Client Socket
pSocket->Close();
POSITION pos,temp;
for(pos = m_connectionList.GetHeadPosition(); pos != NULL;)
{
temp = pos;
// Search for the Socket in the Pointer List
CClientSocket* pSock = (CClientSocket*)m_connectionList.
GetNext(pos);
if (pSock == pSocket)
{
// Found it, so remove it from the Pointer list
// so that no more messages are sent to that Client Socket
m_connectionList.RemoveAt(temp);
break;
}
}
UpdateConnections();
delete pSocket;
if(m_connectionList.GetCount() == 0)
m_msgList.RemoveAll();
}
If you Exit the server by selecting File->Exit, and if there are Clients connected, all the Clients are notified by the Server that it has shut down and all the CClientSocket(s) are closed. This also prevents the Clients from crashing. Following is the code that carries out the task of closing the Client Sockets:
void CChatServerDoc::DeleteContents()
{
// You must initilize m_pSocket to NULL in the Constructor of
// CChatServerDoc, else the server will crash at the start
if(m_pSocket == (CListeningSocket*)NULL)
return;
// Delete the Listening Socket
delete m_pSocket;
m_pSocket = NULL;
CString temp;
if (temp.LoadString(IDS_SERVERSHUTDOWN))
m_msgList.AddTail(temp);
while(!m_connectionList.IsEmpty())
{
// Get a Pointer to the Client Socket
CClientSocket* pSocket = (CClientSocket*)m_connectionList.
RemoveHead();
CMsg* pMsg = AssembleMsg(pSocket , NORMAL_MESSAGE);
//Set Code for Closing
pMsg->m_bClose = TRUE;
// Send Server ShutDowm message to the Client
SendMsg(pSocket, pMsg);
if (!pSocket->IsAborted())
{
// Shut down the Client
pSocket->ShutDown();
BYTE Buffer[50];
while (pSocket->Receive(Buffer,50) > 0);
// Delete the Client Socket
delete pSocket;
}
}
m_msgList.RemoveAll();
if (!m_viewList.IsEmpty())
Message("");
CDocument::DeleteContents();
}
Have fun, Chat to your heart's content, but don't blame me. I developed this by modifying MSDN Sample Chatter and Chatsvr for fun's sake.

Comments
Concise report shows you the incontestable information about chanel and how it may may affect owners.
Posted by emeseesip on 05/06/2013 02:21pmOne Of The Most Detailed adidas Report You Ever Read Or else Your Cash Back [url=http://www.guccija.biz/]ã°ãã é·è²¡å¸[/url] Whoa, wonderful solution. Your corporation got to take a look at nike now while it is still available for sale ! [url=http://www.guccija.biz/]ã°ããããã¼ã±ã¼ã¹[/url] gucci aids every one of us by simply adding a handful of unique functions and characteristics. It is a unvaluable thing for all supporter of adidas. [url=http://www.guccija.biz/]ã°ãã è²¡å¸ æ°ä½[/url] Unbiased statement displays 5 brand new things of nike that nobody is speaking of. [url=http://www.chanelja.biz/]ã·ã£ã㫠財å¸[/url] This is why no-one is covering nike and for these reasons the thing one ought to do this afternoon. [url=http://www.chanelja.biz/]ã·ã£ãã« ãã§ã¼ã³ã¦ã©ã¬ãã[/url] Interesting questions about adidas resolved and the reasons you ought to take a look at each and every term of this specific article. [url=http://www.chanelja.biz/]chanel 財å¸[/url] Techniques of the nike that it's possible to make money from starting up today.[url=http://www.nikeja.biz/]nike[/url] Tips about how to discover all the stuff there is to find out concerning adidas in Four basic steps.
Replysac burberry pas cher
Posted by Acequeacila on 04/30/2013 05:28amChemise Burberry Chemise Burberry Pas Cher burberry homme burberry homme [url=http://chemiseburberryfemme22.webnode.fr/]chemiseburberryfemme22.webnode.fr[/url] , burberry homme [url=http://burberryhomme2.webnode.fr/]burberryhomme2.webnode.fr[/url] , Chemise Burberry
ReplyMemory leak
Posted by John E on 06/14/2009 10:36amThis code in function CLeftView::OnDestroy() causes a small memory leak:- if(m_pImageList != NULL) m_pImageList = NULL; delete m_pImageList; It should really have been this:- if (NULL != m_pImageList) { delete m_pImageList; m_pImageList = NULL; }Replymessenger W/camera and sounds
Posted by prog_agent on 06/24/2006 03:02amhi every body also i wanna to bulid messenger but w/ web camera and sounds not just text messenger i read that i should use (stream buffering server) like online lecture... PLZ PLZ help me if you have any articles or any thing please send it to me PLZ hurryUP thanx alot
ReplyLatest Updates
Posted by barretto_vn on 03/15/2005 08:43amfor updates to this and more of my articles go to http://members.lycos.co.uk/barrettovn Barretto VN
-
-
Replyplease
Posted by comd on 07/22/2009 11:27amsend me too, please comdvas@gmail.com
ReplyPlease send me Chat Program
Posted by blackeyes123 on 05/03/2005 05:40amLink download broken. I need Chat program have control send file betwen clients-server or clients-clients Email: tagore123@gmail.com
Replychat
Posted by Legacy on 11/20/2003 12:00amOriginally posted by: kali
i was very impressed with ur chat source code and the docu....that very nice and now i want to buy the latest
codeguru book.(on visual c++)
iam from india and from Tanuku(andhra pradesh)
and can u pls give the details as where i can get the book
and what is the cost according to indian currency
and
can a get the free edition of any of the vc++ books from u
ReplyCan you do it without the MFCs and use Threads?
Posted by Legacy on 10/13/2003 12:00amOriginally posted by: Naeeym
Hi,
I am trying to develop a program communicating over the net using sockets.I am new in this area. I have used the Winsock control in the Visual Basic to create the sockets and connecting them. But I don't know how to use threads in VB. I have some understanding in C/C++, as I went through your code, I could clearly follow. But the problem is the classes you've used is unavailable in VB(atleast I don't know how to to use them). Any help, pointer would be appreciated.
Thanks,
Naeeym.
ReplyYour Chat in MFC42 included...
Posted by Legacy on 09/22/2003 12:00amOriginally posted by: Lolo
well, your chat software seems to work gut.
Some small mistakes appear when you compile in "MFC42 included" and in Release mode :
the inline declaration for GetDocument() in the class CInputView is missing.
The constant String "IDS_CREATEFAILED" in the res needs to
be appended to another value (62000 for ex.) since your are using one from MS ressource.
I tried with a LAN network with 2 clients, it's OK.
have a good time...
Laurent.
ReplyInstall
Posted by Legacy on 07/25/2003 12:00amOriginally posted by: grzybek
Hi,
It's excellent program.
How can I install it on other clients?
There are missing some *.dll files, maybe
how to create install version ?
Thanks,
Replygrzybek
client-server chat page
Posted by Legacy on 06/19/2003 12:00amOriginally posted by: mvs narasimhulu
It was excellent
Reply