Click here to Skip to main content
13,258,269 members (52,095 online)
Click here to Skip to main content
Add your own
alternative version


133 bookmarked
Posted 25 Mar 2003

CAsyncSocketEx - Replacement for CAsyncSocket with proxy and SSL support

, 5 Apr 2003
Rate this:
Please Sign up or sign in to vote.
CAsyncSocketEx is an MFC-less replacement for CAsyncSocket which does also offer a flexible layer system. With the layer class CAsyncProxySocketLayer, you can connect through proxy servers.


CAsyncSocketEx is an MFC-less replacement for CAsyncSocket which does also offer a flexible layer code. This class was written because CAsyncSocket is not the fastest WinSock wrapper and it's very hard to add new functionality to CAsyncSocket derived classes. This class supports most of the features of CAsyncSocket and can be extended quite easily. With the layer system, you can implement transparent layers like proxy or SSL layers easily.

One benefit is, that CAsyncSocketEx works without MFC, but if MFC is enabled (_AFX is defined), CAsyncSocketEx offers some functions taking a CString as argument, so that CAsyncSocketEx is compatible with CAsyncSocket.

CAsyncProxySocketLayer is a layer class for CAsyncSocketEx. With it's help, you can connect through proxy servers. This layer is almost transparent, so you won't have to modify much code to use it. Other layers can be written quite easily as well, just derive new layer classes from CAsyncSocketExLayer.

Another layer class is CAsyncSslSocketLayer, which can be used to establish SSL connections to servers.

Using the code

To use CAsyncSocketEx, just replace all occurrences of CAsyncSocket in your code with CAsyncSocketEx. If you did not enhance CAsyncSocket yourself in any way, you won't have to change anything else in your code. However, problems can occur if you're using IOCtl or SetSockOpt in your code, CAsyncSocketEx and the layer classes do not recognize if you change any options using IOCtl or SetSockOpt.

CAsyncSocketEx provides some useful new functions:

// Triggers an event on the socket
// Any combination of FD_READ, FD_WRITE, FD_CLOSE, 
//FD_ACCEPT, FD_CONNECT and FD_FORCEREAD is valid for lEvent.
BOOL TriggerEvent(long lEvent);

With TriggerEvent you can explicitly trigger the notification messages handled in OnReceive, OnSend, ...

TriggerEvent(FD_SEND); for example posts a message to the internal helper window and returns. Later, if this message is processed, OnSend will be called.

There's something special about FD_READ: OnRecieve will only be called if there is really any data available. To trigger a call to OnReceive regardless of data waiting or not, use FD_FORCEREAD instead.

The other new functions are for the new layer system.

Using the layer system

Using the layer system is really simple. In most cases, it is sufficient to create a new instance of a layer class and attach it to a CAsyncSocketEx instance.

//Attaches a new layer to the socket.
BOOL AddLayer(CAsyncSocketExLayer *pLayer);

This adds a new layer derived from CAsyncSocketExLayer to the socket. You can add more than one layer. The layer last added to the layer list, works directly on the socket and the other layers operate on the previous one. All calls you make to CAsyncSocketEx are first handled by the layer first added to the list. Example: If you want to establish an SSL connection to a server over a proxy server, first add the SSL layer (see the CAsyncSslSocketLayer article), then add the proxy layer.

//Resets layer chain.
void RemoveAllLayers()

This function detached all layers from the socket. But it does not destroy the layer class instances, you are still responsible for destroying the layer instances. In theory, it would be possible to add a layer previously detached from a socket to a new socket, but this is not recommended. You should create and attach a new instance of the layer for each established connection.

//Called by the layers to notify application of some events
virtual int OnLayerCallback(const CAsyncSocketExLayer *pLayer, 
                            int nType, int nParam1, int nParam2);

This function is called by the layers to notify the program about more or less important events of the layer. The first parameter identifies the layer which did send the notification message. The second parameter is the type of the notification. Valid notification types are:


    This notification is sent if the state of the layer has changed. nParam1 contains the new state, nParam2 contains the old state. Valid states are:

    • 0 - Not a valid socket
    • 1 - Unconnected
    • 2 - Connecting
    • 3 - Listening
    • 4 - Connected
    • 5 - Closed
    • 6 - Aborted

    This notification is sent on events specific to a each layer. See the layer's description for the meaning and the parameters of this notification message.


With this layer you can connect through proxy servers. This class supports SOCKS4/5 as well as HTTP/1.1 (using CONNECT method) proxies. For more information about SOCKS4/5 go to, for more information about HTTP 1.1 go to and search for RFC2616.

You don't have to change much, in your already existing code, to use CAsyncProxySocketLayer. To use it, create an instance of CAsyncProxySocketLayer, call SetProxy and attach it to a CAsyncSocketEx instance. You have to process OnLayerCallback in your CAsyncSocketEx instance as it will receive all layer notifications.

The following notifications are sent (of type LAYERCALLBACK_LAYERSPECIFIC):

  • Error codes:
    PROXYERROR_NOCONN 1Can't connect to proxy server, use GetLastError for more information
    PROXYERROR_REQUESTFAILED 2Request failed, can't send data
    PROXYERROR_AUTHREQUIRED 3 Authentication required
    PROXYERROR_AUTHTYPEUNKNOWN 4 Authtype unknown or not supported
    PROXYERROR_AUTHFAILED 5 Authentication failed
  • Status messages:
    PROXYSTATUS_LISTENSOCKETCREATED 8Called when a listen socket was created successfully. Unlike the normal listen function, a socksified socket has to connect to the proxy to negotiate the details with the server on which the listen socket will be created. The two parameters will contain the IP and port of the listen socket on the server.

If you want to use CAsyncProxySocketLayer to create a listen socket, you have to use this overloaded function:

BOOL PrepareListen(unsigned long serverIp);

serverIP is the IP of the server you are already connected through the SOCKS proxy. You can't use listen sockets over a SOCKS proxy without a primary connection. Listen sockets are only supported by SOCKS proxies, this won't work with HTTP proxies.

When the listen socket is created successfully, the PROXYSTATUS_LISTENSOCKETCREATED notification is sent. The parameters will tell you the IP and the port of the listen socket. After it, you have to handle the OnAccept message and accept the connection.

Be careful when calling Accept: rConnected socket will NOT be filled! Instead use the instance which created the listen socket, it will handle the data connection.

If you want to accept more than one connection, you have to create a listing socket for each of them!

Description of important functions and their parameters:

void SetProxy(int nProxyType);
void SetProxy(int nProxyType, CString ProxyHost, int nProxyPort);
void SetProxy(int nProxyType, CString ProxyHost, int nProxyPort,
                            CString ProxyUser, CString ProxyPass);

Call one of this functions to set the proxy type.


  • nProxyType specifies the Proxy Type.
  • ProxyHost and nProxyPort specify the address of the proxy
  • ProxyUser and ProxyPass are only available for SOCKS5 proxies.

Supported proxy types:


There are also some other functions:

int GetProxyType();

Returns the used proxy.

const int GetLastProxyError() const;

Returns the last proxy error, see above for a list of available error codes.

Known limitations

  • blocking mode not supported
  • IOCtl / SetSockOpt not fully supported, use with caution.
  • SOCK_DGRAM (UDP) is not supported, only SOCK_STREAM (TCP) is supported.

Version History

  • 2003-03-29 - small fixes
  • 2003-03-28 - Connect now uses WSAAsyncGetHostByName to resolve host names, no longer blocking whole thread
  • 2003-03-26 - First public release


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

Tim Kosse
Web Developer
Germany Germany
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionCASH ACCESS DENIED Trough Proxy Pin
Zak Chapman1-Mar-14 15:13
professionalZak Chapman1-Mar-14 15:13 
QuestionCAsyncSocketEx has the same defects with CAsyncSocke, too? Pin
ehaerim20-Nov-13 0:54
memberehaerim20-Nov-13 0:54 
QuestionCompile error in VS 2010 Pin
MRyndin16-Oct-12 21:44
memberMRyndin16-Oct-12 21:44 
Questionhow to I use this in console application? Pin
vvvjjj23-Apr-12 21:11
membervvvjjj23-Apr-12 21:11 
QuestionCan this code work in service? Pin
onegg27-Mar-12 0:43
memberonegg27-Mar-12 0:43 
QuestionAnyone has ever used this class on Win 7 64 bit? Pin
ehaerim3-Mar-12 22:25
memberehaerim3-Mar-12 22:25 
QuestionGood Job, Guys Pin
juexing15-Aug-11 22:59
memberjuexing15-Aug-11 22:59 
GeneralBravo - did what it said on the tin, only one slight fix needed Pin
watta28-Apr-11 4:54
memberwatta28-Apr-11 4:54 
GeneralRe: Bravo - did what it said on the tin, only one slight fix needed Pin
ehaerim3-Mar-12 14:02
memberehaerim3-Mar-12 14:02 
I don't think it's a good idea to handle WSAEWOULDBLOCK inside this method.

From MSDN, the return value of CAsyncSocket::Connect is
Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError. If this indicates an error code of WSAEWOULDBLOCK, and your application is using the overridable callbacks, your application will receive an OnConnect message when the connect operation is complete. The following errors apply to this member function:

That is, WSAEWOULDBLOCK is an error(even though it is a special one in some respects), not a success.

Your fix returns TRUE on WSAEWOULDBLOCK, whereas MFC CAsyncSocket::Connect returns FALSE. So, your fix makes CAsyncSocketEx incompatible (at least not 100% compatible) with CAsyncSocket.

Rather, you should handle WSAEWOULDBLOCK after the call to Connect returns.
Generalfail to connect to specific server through proxy server Pin
chentsiushu4-Dec-08 22:14
memberchentsiushu4-Dec-08 22:14 
GeneralRe: fail to connect to specific server through proxy server Pin
chentsiushu4-Dec-08 22:20
memberchentsiushu4-Dec-08 22:20 
GeneralCannot just replace CASYNCSOCKET as mentioned Pin
Aeln4-Nov-08 2:08
memberAeln4-Nov-08 2:08 
QuestionCAsyncSocketEx::Create fails when WSAStartup is not called in advance? Pin
ehaerim12-Oct-07 22:43
memberehaerim12-Oct-07 22:43 
GeneralTCP/IP socket programming in DOS Pin
mehrdadsilver28-Dec-06 22:04
membermehrdadsilver28-Dec-06 22:04 
GeneralRe: TCP/IP socket programming in DOS Pin
VuNic8-Dec-06 22:53
memberVuNic8-Dec-06 22:53 
QuestionHow to use it in HTTP protocol? Pin
xnetec5-Dec-06 19:36
memberxnetec5-Dec-06 19:36 
QuestionIS there an updated version available? Pin
tparry13-Oct-06 5:49
membertparry13-Oct-06 5:49 
AnswerRe: IS there an updated version available? Pin
Mr Wonk25-Oct-06 5:38
memberMr Wonk25-Oct-06 5:38 
QuestionHow about using CAsyncSocket::m_hSocket member variablie? [modified] Pin
ehaerim22-Jul-06 13:29
memberehaerim22-Jul-06 13:29 
QuestionUsable for SSL Server ? Pin
DavidXanatos3-Jul-06 0:18
memberDavidXanatos3-Jul-06 0:18 
QuestionHow to obtain proxy server info? [modified] Pin
wang_hunter9716-Jun-06 0:41
memberwang_hunter9716-Jun-06 0:41 
QuestionImplementation of CSocket for this? Pin
deh2k12-Jun-06 12:26
memberdeh2k12-Jun-06 12:26 
QuestionHow to use it in ATL project? Pin
at200015-May-06 7:29
memberat200015-May-06 7:29 
QuestionCAsyncSocketEx can not send anything Pin
xnetec21-Sep-05 20:16
memberxnetec21-Sep-05 20:16 
JokeRe: CAsyncSocketEx can not send anything Pin
xnetec10-Mar-06 3:24
memberxnetec10-Mar-06 3:24 
GeneralRe: CAsyncSocketEx can not send anything Pin
rsmania20-Mar-06 0:11
memberrsmania20-Mar-06 0:11 
GeneralRe: CAsyncSocketEx can not send anything Pin
xnetec7-May-06 7:06
memberxnetec7-May-06 7:06 
Generalproblem with nConnectionBackLog Pin
juanvicr14-May-05 12:33
memberjuanvicr14-May-05 12:33 
GeneralMemory Leak!!! Pin
Onni Qvickstrom9-May-05 5:58
sussOnni Qvickstrom9-May-05 5:58 
GeneralConnect bug fix Pin
Andrew K3-May-05 8:17
memberAndrew K3-May-05 8:17 
GeneralRe: Connect bug fix Pin
ehaerim5-Dec-09 9:37
memberehaerim5-Dec-09 9:37 
GeneralRe: Connect bug fix Pin
watta28-Apr-11 4:57
memberwatta28-Apr-11 4:57 
QuestionMFC-less? Pin
Mars10512-Mar-05 7:38
sussMars10512-Mar-05 7:38 
GeneralProxy change Pin
imadulhaq7-Mar-05 21:59
memberimadulhaq7-Mar-05 21:59 
GeneralOnReceive Event Pin
Pixbyte1-Feb-05 4:40
memberPixbyte1-Feb-05 4:40 
QuestionCHtmlView??? Pin
Rafkat27-Nov-04 2:51
memberRafkat27-Nov-04 2:51 
GeneralNon-MFC usage Pin
sergeyv200230-Sep-04 7:04
membersergeyv200230-Sep-04 7:04 
GeneralHelp me! I want get message from Web Browser Pin
baoiph21-Apr-04 16:31
memberbaoiph21-Apr-04 16:31 
QuestionCan you give me a example code of how to make a listenning socket by CAsyncSocketEx Pin
raobo2-Feb-04 5:35
memberraobo2-Feb-04 5:35 
GeneralWhy listen socket fail Pin
Anonymous29-Jan-04 20:01
sussAnonymous29-Jan-04 20:01 
QuestionHow to interpret the response? Pin
NaveenMankotia26-Jan-04 23:49
memberNaveenMankotia26-Jan-04 23:49 
QuestionHow To Do using complete port or overlapped IO Pin
yxu@corp.ceiea.com26-Dec-03 15:23
memberyxu@corp.ceiea.com26-Dec-03 15:23 
AnswerRe: How To Do using complete port or overlapped IO Pin
Tim Kosse29-Dec-03 10:37
memberTim Kosse29-Dec-03 10:37 
QuestionAny error in your demo??? Pin
Mongris5-Dec-03 23:04
memberMongris5-Dec-03 23:04 
AnswerRe: Any error in your demo??? Pin
Tim Kosse10-Dec-03 4:53
memberTim Kosse10-Dec-03 4:53 
GeneralRe: Any error in your demo??? Pin
Mongris10-Dec-03 15:00
memberMongris10-Dec-03 15:00 
GeneralI want to Ask a question Pin
gjp1730224-Nov-03 17:26
membergjp1730224-Nov-03 17:26 
GeneralWhy error occur? Thanks Pin
raobo8-Nov-03 7:03
memberraobo8-Nov-03 7:03 
GeneralRe: Why error occur? Thanks Pin
Tim Kosse8-Nov-03 8:29
memberTim Kosse8-Nov-03 8:29 
GeneralRe: Why error occur? Thanks Pin
raobo10-Nov-03 1:04
memberraobo10-Nov-03 1:04 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171114.1 | Last Updated 6 Apr 2003
Article Copyright 2003 by Tim Kosse
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid