65.9K
CodeProject is changing. Read more.
Home

CAsyncsocket and Console with MFC / TCP

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.22/5 (5 votes)

Jul 8, 2013

CPOL

1 min read

viewsIcon

26054

downloadIcon

1883

How to use CAsyncSocket in a console application? Is it possible at all?

Introduction

First of all, thanks to Jobin Wilson for this article. It has shown me the principles on which I could build up my solution. You can see it in the wide match in code.

Background

I wanted to pick out the answer to the often asked question: How to use CAsyncSocket in a console application? Is it possible at all?

Using the Code

For me, this question was important because I had to build a Central Communication Manager which coordinates Requests and Services.

About that issue, I see two answers: Yes, it's possible to use CAsyncSocket with full features without a CWin window. No, it's no common Console App. And it works fine. :-)

You need a CWorker class derived from CWinApp, because CWinApp:CWinThread has the MFC-Message-Loop Run().

class CWorkerApp :public CWinApp; 

Second, you need your CAsync class derived from CAsyncSocket to override the virtual Callbacks.

class CAsync :public CAsyncSocket; 

Third, you must tell CWinApp to run without a CWin-dialog, because by default it stops if it has no window.

AfxOleSetUserCtrl(FALSE);

Keep in mind, you have no UI to that app. You just see it in Task-Manager under Processes and you can Kill it only that way. But the good thing is you can allocate a Console window to put your DEBUG output there.
The rest I found in MSDN documentation, Sample EchoServer, and "of course" in the Internet :))

The full source consists of:

  • MyEchoSocket.h
  • EchoServer.h
  • MyEchoSocket.cpp
  • EchoServer.cpp
  • StdAfx.h
  • StdAfx.cpp

Just a note to the source files: There is also a file:

  • TCPcl.cpp

It is a Win32 Console App with Windows Sockets in blocking mode, intended for testing the CAsyncSocket server.