Asynchronous Windows Socket Class

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

The async_socket class represents a Windows Socket.
It is similar CAsyncSocket MFC class,
but it differs that does not use a message queue of the application.
It uses overlapped operations.
Therefore it can be used in the console applications.

For usage of this class you probably should override some virtual
notification functions. Such as:


//Called when connection closed by remote host
//err – WinSock error code
virtual void on_close(int err);

//Called when new connection request is received
//err – WinSock error code
virtual void on_accept(int err);

//Called when socket is ready for receiving data
//err – WinSock error code
virtual void on_read(int err);

//Called when socket is ready for sending data
//err – WinSock error code
virtual void on_write(int err);

//Called when socket is completely created and
// watching thread is started
//err – WinSock error code
virtual void on_attach();

//Called when overlapped read operation is done
//err – Win32 error code
virtual void on_read_complete(DWORD err, DWORD len);

//Called when overlapped write operation is done
//err – Win32 error code
virtual void on_write_complete(DWORD err, DWORD len);

//Called before watching thread will be destroyed
virtual void on_clear();

virtual void on_timeout();

To create connected node, following tasks should be performed

  1. Derive class from async_socket.
  2. Override on_attach function,
    which called first when socket is created.
    In this function you can start
    read and/or write operation by calling bool read(char* pBuff, DWORD len)
    and/or bool write(char* pBuff, DWORD len) functions.
  3. Override on_read_complete function, if you will receive data.
  4. Override on_write_complete function, if you will transmit data.
  5. For listening socket you must override on_accept,
    which notifies that it can accept pending connection requests
    by calling accept function.
  6. Also you should call select (usually from on_attach) with
    appropriate flags for obtaining the notifications (if needed).

Important! Do not forget about multitasking and safety of data, all
notification functions are called from watching thread.

The demo project contains implementation of the HTTP/1.1 server
based on the async_socket class. There some auxiliary
classes also are contained.

Downloads

Download demo project – 97 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read