Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / MFC

CAsyncsocket and Console with MFC / TCP

4.22/5 (5 votes)
24 May 2016CPOL1 min read 26.1K   1.9K  
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().

C++
class CWorkerApp :public CWinApp; 

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

C++
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.

C++
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)