
Introduction
This is a really simple application you to all have greate experience in Socket communication. And not only that how to handle worker threads with CSocket objects to support multiple clients. I have spend weeks, to get an idea about this. I searched in lot of sites, papers, books just to do it in simple way as I do now. But I have to say they help me to understand some form of functionalities in VC++. So finally I put all what I understood into one and created this simple infrastructure application to support multiple clients.
Structure of the application
This is a simple dialog based application. I my Dialog window class I have only two buttons to start and stop the server. Once you click on start server It will create Listner thread to listen to the client. So it always wait at the Accept method of the socket. So once client got connected to my server Accept method of the socket will get fire.
Then I am getting the connection object and I'll retreive the handle for that. SOCKET handle is a global variable just to refer it in my client handler thread. Inside the accept, I am creating my second thread to handle my newly created client socket. So all the messages comming from that client is handled inside of this thread.
There are nother 2 global variables just to keep the track of created threads and and handles. this is very useful when you want to shutdown the sockets and terminate the threads.
This is the heart of the program.
UINT ListenThread(LPVOID pParam)
{
AfxSocketInit();
CieGServerDlg *Dlg= (CieGServerDlg*)pParam;
CSocket Listen;
CibCommon iCom;
int iPort;
CString strPort;
iPort = atoi(iCom.readFromRegistry("IEGSERVER","PORT_ID","9000"));
strPort.Format("%d",iPort);
Listen.Create(iPort);
hServerHandle = Listen.m_hSocket;
if(Listen.Listen())
{
CliHandleList.RemoveAll();
CliThreadList.RemoveAll();
int i=0;
while(Dlg->m_bRunServer)
{
CSocket * pCSock=new CSocket();
if(Listen.Accept(*pCSock))
{
hClinetHandle = pCSock->Detach();
CliHandleList.AddHead(&hClinetHandle);
CliThreadList.AddHead(AfxBeginThread(RequestHandler,0));
delete pCSock;
}
else
{
delete pCSock;
}
}
}
else
{
CString strMsg;
strMsg.Format("Unable to open requested port %s to this server. May be server running on this port. Please specify another port and start server again.",strPort);
Dlg->m_ctrlBUTTONStop.EnableWindow(false);
Dlg->m_ctrlBUTTONStart.EnableWindow(true);
Dlg->m_ctrlSTATICFlag.SetBitmap(Dlg->m_bmpRed);
Dlg->m_bRunServer = false;
AfxMessageBox(strMsg);
Dlg->ShowWindow(SW_NORMAL);
}
return 0;
}
I think you will enjoy this, and I am really thank full to the people of code project to have a site like this to help others and to learn.
From this same prgram you can learn how you can write a program to read and write to windows registry. In my CibCommon class, I have implemented this code to use when ever I
I want to write and read from registry.
If you have questions I am relly glad to help you.
Thank you
Venura