Click here to Skip to main content
11,924,280 members (56,144 online)
Click here to Skip to main content
Add your own
alternative version


117 bookmarked

Socket Programming with MFC (Part 1)

, 9 Nov 2005
Rate this:
Please Sign up or sign in to vote.
An article on Socket Programming with MFC
Sample Image - MFCSockets.jpg


Socket Programming is a very interesting activity in most of the programming languages. It's a nice activity to write Servers and Clients that communicate over a network. In Windows Platform, socket communications are based on Microsoft Winsock architecture. Windows supports both stream based (TCP) and Datagram based (UDP) socket communication. Windows APIs are available for socket programming, but many find it difficult to work with them.

So here I am going to explain the easiest way to do socket programming using MFC socket classes. This will not only make your job easy, but will also reduce the development time for your network applications. You can develop a custom made socket class that you can reuse in all the network based applications that you write. I will explain these concepts by developing an Echo Server application.

The MFC Socket Classes

For Socket programming, MFC provides two built in classes named CAsyncSocket and CSocket. CSocket is inheriting its functionality from CAsyncSocket. CAsyncSocket class provides several notification functions ,that will be called automatically upon occurrence of the socket events. Moreover, it acts as the base class for the complete event driven socket communication.

We can create our own customised socket classes by inheriting from CAsyncSocket class, which will serve our application specific needs. At first socket environment needs to be initialized by calling the AfxSocketInit() function.

Initializing Sockets

To initialize sockets, we need to call the function AfxSocketInit(). It is usually called from the InitInstance() function of the MFC application. If we are using a wizard to generate the application, checking the option "use Windows Sockets" will automatically do this job for us. It returns a value to indicate success or failure of the call.

BOOL CEchoServerApp::InitInstance()
if( AfxSocketInit() == FALSE)
  AfxMessageBox("Sockets Could Not Be Initialized"); 
  return FALSE; 

Creating Server Sockets

To create a Server socket, we need to declare a variable of type CAsyncSocket or our own class derived from CAsyncSocket or CSocket. Then we must call the create() function with the port to be listened as argument. It returns a value to indicate success or failure of the call:

AfxMessageBox("Unable to Listen on that port, please try another port"); 

Creating Client Sockets

To create a Client socket, first we need to declare a variable of type CAsyncSocket or our own class derived from CAsyncSocket or CSocket. Then we must call the create() function without any arguments. It returns a value to indicate success or failure of the call:

m_sConnected.Connect("server ip",port);

Listening for Incoming Connections

For making the server socket listen to the Specific port, we must call the function Listen(). It returns a value to indicate success or failure of the call:

if( m_sListener.Listen()== FALSE) 
AfxMessageBox("Unable to Listen on that port, please try another port"); 

Accepting Connections

The incoming connection must be accepted to another socket (not the listening socket). It is done by calling the Accept function with the second socket as argument.

void CEchoServerDlg::OnAccept()
 CString strIP; 
 UINT port; 
  m_status="Client Connected,IP :"+ strIP; 
  m_sConnected.Send("Connected To Server",strlen("Connected To  Server"));      
 AfxMessageBox("Cannot Accept Connection"); 

Sending Data

The data to be sent is kept in a buffer and a pointer to it and its length is passed to the send function:


Receiving Data

Data is received by calling the function receive(buffer,maxlength):

void CEchoServerDlg::OnReceive() 
char *pBuf =new char [1025]; 
CString strData; 
int iLen;
if(iLen == SOCKET_ERROR)      
  AfxMessageBox("Could not Receive");      
 //display in server              
 m_sConnected.Send(pBuf,iLen);  //send the data back to the Client   
 delete pBuf;          

Shutting Down Connection

m_sConnected.ShutDown(0);    Stops  Sending Of Data 
m_sConnected.ShutDown(1);    Stops Receiving of data
m_sConnected.ShutDown(2);    Stops Both Sending and Receiving of Data

Closing Connection


Socket Events

Several functions are used for notification of events. They are to be overridden by descendant classes, in the form of protected member functions.

  1. OnAccept() indicates that a connection is pending to be accepted
  2. OnClose() indicates that application at the other end has closed the socket
  3. OnConnect() indicates that Connection establishment is complete
  4. OnSend() indicates that Data is being sent
  5. OnReceive() indicates that Data is being received
  6. OnOutofBandData() indicates that out of band data (urgent message) has arrived

Deriving Our Own Socket Class from CAsyncSocket

For deriving our own socket class, go to class view and add a new class and set its base class as CAsyncSocket. With the help of classwizard, add notification functions as shown below:

class MyEchoSocket : public CAsyncSocket
{ // Attributes 
 // Operations
virtual ~MyEchoSocket(); 
// Overrides 
void SetParentDlg(CDialog *pDlg);// ClassWizard generated virtual function overrides 
virtual void OnAccept(int nErrorCode);
virtual void OnClose(int nErrorCode);
virtual void OnConnect(int nErrorCode);
virtual void OnOutOfBandData(int nErrorCode);
virtual void OnReceive(int nErrorCode); 
virtual void OnSend(int nErrorCode); 
//}}AFX_VIRTUAL // Generated message map functions 
// NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG 
CDialog * m_pDlg; 

Setting The "Parent Dialog"

The socket class's SetParentDlg function is called to ensure that notifications are received to the dialog class when socket events occur:


Linking Socket Events With Dialog Class Member Functions

In the dialog class, add the appropriate functions like:

void OnReceive(); 
void OnClose(); 
void OnAccept(); 
void OnConnect();

These functions are called from the socket class as shown below:

void MyEchoSocket::OnAccept(int nErrorCode) 
// TODO: Add your specialized code here and/or call the base class 

Using the Code

The attached project is ready to be compiled and executed. Just open with Visual C++ 6.0 and compile. It is an EchoServer that echoes back whatever data is sent to it. You can use a telnet client to connect to it. The sending and receiving functionality can be tested easily from telnet console.


  • Version 1.0, Part 1 of MFC Socket Programming [ 10/11/2005 ]


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


About the Author

Jobin Wilson
Web Developer
United States United States

You may also be interested in...

Comments and Discussions

QuestionRunning Echo Server Pin
Ivan Chemelekov9-Aug-15 17:22
memberIvan Chemelekov9-Aug-15 17:22 
QuestionConnection Time-out in Client Side Pin
Moharram28-Dec-14 20:47
memberMoharram28-Dec-14 20:47 
QuestionError C3861: 'AfxSocketInit': identifier not found Pin
indra30405-Nov-13 20:50
memberindra30405-Nov-13 20:50 
GeneralMy vote of 5 Pin
JasMineLeaf17-Oct-13 22:23
memberJasMineLeaf17-Oct-13 22:23 
QuestionSetParentdlg Pin
yossisw26-Aug-13 0:38
memberyossisw26-Aug-13 0:38 
GeneralMy vote of 5 Pin
Member 1012532125-Jun-13 5:55
memberMember 1012532125-Jun-13 5:55 
Questionthankssssss Pin
Member 999976523-May-13 9:02
memberMember 999976523-May-13 9:02 
GeneralMy vote of 4 Pin
iampradeepsharma26-Feb-13 20:22
memberiampradeepsharma26-Feb-13 20:22 
GeneralMy vote of 2 Pin
Member 92600623-Jan-13 22:41
memberMember 92600623-Jan-13 22:41 
GeneralMy vote of 5 Pin
nethajiprasath26-Jun-12 1:56
membernethajiprasath26-Jun-12 1:56 
QuestionClient? Pin
L12345M629-Mar-11 6:49
memberL12345M629-Mar-11 6:49 
Questiontelnet send: only 64 characters at one time? Pin
L12345M69-Mar-11 5:14
memberL12345M69-Mar-11 5:14 
QuestionHow to add a timeout? Pin
L12345M68-Mar-11 4:24
memberL12345M68-Mar-11 4:24 
AnswerRe: How to add a timeout? Pin
L12345M614-Mar-11 5:53
memberL12345M614-Mar-11 5:53 
GeneralMFC project options Pin
bkelly1319-Nov-10 17:43
memberbkelly1319-Nov-10 17:43 
QuestionHow to communicate between TCP Client and UDP Server. Pin
ksrithesh18-Feb-10 21:25
memberksrithesh18-Feb-10 21:25 
General[Message Deleted] Pin
it.ragester2-Apr-09 22:56
memberit.ragester2-Apr-09 22:56 
Questionhow to create multi client communication Pin
N.Ravi Raj1-Dec-08 19:05
memberN.Ravi Raj1-Dec-08 19:05 
GeneralConnecting multiple clients to one port. Pin
Tpasta2-Jul-08 6:14
memberTpasta2-Jul-08 6:14 
GeneralRe: Connecting multiple clients to one port. Pin
L12345M621-Mar-11 0:50
memberL12345M621-Mar-11 0:50 
GeneralRe: Connecting multiple clients to one port. Pin
L12345M621-Mar-11 4:41
memberL12345M621-Mar-11 4:41 
QuestionHow can i do UDP socket programming Pin
buntyrolln5-Jun-08 20:30
memberbuntyrolln5-Jun-08 20:30 
Generalgood source Pin
Ahn Jung Woo13-Sep-07 18:39
memberAhn Jung Woo13-Sep-07 18:39 
GeneralSocket multi-language Pin
proITer4-Sep-07 19:34
memberproITer4-Sep-07 19:34 
Questionproblem with connecting to a server. Pin
nishchal_devnur25-Jun-07 1:30
membernishchal_devnur25-Jun-07 1:30 
QuestionUsing CAsyncSocket in a Console Application ??? Pin
lutzTobias19-Apr-07 3:30
memberlutzTobias19-Apr-07 3:30 
QuestionPlease explain the objective of this project... Pin
shampyshanky25-Mar-07 0:22
membershampyshanky25-Mar-07 0:22 
AnswerRe: Please explain the objective of this project... Pin
thenotwist28-Jul-07 15:12
memberthenotwist28-Jul-07 15:12 
Generalproblem in transfeering contexts Pin
Vishwas Bharadwaj7-Feb-07 9:15
memberVishwas Bharadwaj7-Feb-07 9:15 
QuestionHow to test this application? Pin
MikeRT23-Nov-06 20:28
memberMikeRT23-Nov-06 20:28 
AnswerRe: How to test this application? Pin
Jobin Wilson29-Nov-06 20:30
memberJobin Wilson29-Nov-06 20:30 
GeneralRe: How to test this application? Pin
bertszoghy30-Jan-07 14:01
memberbertszoghy30-Jan-07 14:01 
AnswerRe: How to test this application? Pin
Nigel I15-Sep-07 5:30
memberNigel I15-Sep-07 5:30 
GeneralRe: How to test this application? Pin
Nigel I15-Sep-07 6:02
memberNigel I15-Sep-07 6:02 
AnswerRe: How to test this application? Pin
iampradeepsharma26-Feb-13 20:27
memberiampradeepsharma26-Feb-13 20:27 
GeneralCAsyncSocket in MFC console application Pin
hhjoker131-Aug-06 23:58
memberhhjoker131-Aug-06 23:58 
GeneralRe: CAsyncSocket in MFC console application Pin
ram on vc++15-Oct-06 3:58
memberram on vc++15-Oct-06 3:58 
GeneralRe: CAsyncSocket in MFC console application Pin
Jobin Wilson29-Nov-06 20:24
memberJobin Wilson29-Nov-06 20:24 
QuestionRe: CAsyncSocket in MFC console application Pin
MasthanRao28-Dec-06 16:33
memberMasthanRao28-Dec-06 16:33 
Generalcannot coonnect with telnet Pin
samreengr819-Apr-06 8:05
membersamreengr819-Apr-06 8:05 
GeneralRe: cannot coonnect with telnet Pin
Jobin Wilson27-Apr-06 0:07
memberJobin Wilson27-Apr-06 0:07 
GeneralCSocket or CAsyncSocket Pin
Vinaya22-Feb-06 19:10
memberVinaya22-Feb-06 19:10 
GeneralRe: CSocket or CAsyncSocket Pin
Jobin Wilson27-Apr-06 0:11
memberJobin Wilson27-Apr-06 0:11 
GeneralRe: CSocket or CAsyncSocket Pin
nilrshkorpe9-May-06 3:22
membernilrshkorpe9-May-06 3:22 
GeneralI'm doing something wrong Pin
kbsoftware2-Feb-06 19:00
memberkbsoftware2-Feb-06 19:00 
GeneralRe: I'm doing something wrong Pin
Vinaya22-Feb-06 19:16
memberVinaya22-Feb-06 19:16 
QuestionTCP or UDP Pin
kestrel_chan19-Jan-06 8:59
memberkestrel_chan19-Jan-06 8:59 
AnswerRe: TCP or UDP Pin
Jobin Wilson3-May-06 0:38
memberJobin Wilson3-May-06 0:38 
Questionwhy the connect is rejected?? Pin
howareyouimfine21-Nov-05 16:51
memberhowareyouimfine21-Nov-05 16:51 
AnswerRe: why the connect is rejected?? Pin
Jobin Wilson28-Nov-05 23:23
memberJobin Wilson28-Nov-05 23:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.151125.3 | Last Updated 10 Nov 2005
Article Copyright 2005 by Jobin Wilson
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid