C++
  Home arrow C++ arrow Page 2 - A Reusable Windows Socket Server Class Wit...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

A Reusable Windows Socket Server Class With C++
By: Len Holgate
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 41
    2002-06-28

    Table of Contents:
  • A Reusable Windows Socket Server Class With C++
  • What does a socket server need to do?
  • Asynchronous IO
  • Some example servers
  • Chunking the byte stream (Contd.)
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    A Reusable Windows Socket Server Class With C++ - What does a socket server need to do?


    (Page 2 of 6 )

    A socket server needs to be able to listen on a specific port, accept connections and read and write data from the socket. A high performance and scaleable socket server should use asynchronous socket IO and IO completion ports. Since we're using IO completion ports we need to maintain a pool of threads to service the IO completion packets. If we were to confine ourselves to running on Win2k and above we could use the QueueUserWorkItem api to deal with our threading requirements but to enable us to run on the widest selection of operating systems we have to do the work ourselves.

    Before we can start accepting connections we need to have a socket to listen on. Since there are many different ways to set such a socket up, we'll allow the user's derived class to create this socket by providing a pure virtual function as follows:

    virtual SOCKET CreateListeningSocket(
    unsigned long address,
    unsigned short port) = 0;


    The user's class can now implement this function as they see fit, a common implementation might be something like this:

    SOCKET CSocketServer::CreateListeningSocket(
    unsigned long address,
    unsigned short port)
    {
    SOCKET s = ::WSASocket(AF_INET, SOCK_STREAM, IPPROTO_IP, NULL, 0, WSA_FLAG_OVERLAPPED);
    if (s == INVALID_SOCKET)
    {
    throw CWin32Exception(_T("CSocket::CreateListeningSocket()"), ::WSAGetLastError());
    }
    CSocket listeningSocket(s);
    CSocket::InternetAddress localAddress(address, port);
    listeningSocket.Bind(localAddress);
    listeningSocket.Listen(5);
    return listeningSocket.Detatch();
    }


    Note that we use a helper class, CSocket, to handle setting up our listening socket. This class acts as a "smart pointer" for sockets, automatically closing the socket to release resources when it goes out of scope and also wraps the standard socket API calls with member functions that throw exceptions on failure.

    Now that we have a socket to listen on we can expect to start receieving connections. We'll use the WSAAccept() function to accept our connections as this is easier to use than the higher performance AcceptEx() we'll then compare the performance characteristics with AcceptEx() in a later article.

    When a connection occurs we create a Socket object to wrap the SOCKET handle. We associate this object with our IO completion port so that IO completion packets will be generated for our asynchronous IO. We then let the derived class know that a connection has occurred by calling the OnConnectionEstablished() virtual function. The derived class can then do whatever it wants with the connection, but the most common thing would be to issue a read request on the socket after perhaps writing a welcome message to the client.

    void CSocketServer::OnConnectionEstablished(
    Socket *pSocket,
    CIOBuffer *pAddress)
    {
    const std::string welcomeMessage("+OK POP3 server readyrn");
    pSocket->Write(welcomeMessage.c_str(), welcomeMessage.length());
    pSocket->Read();
    }

    More C++ Articles
    More By Len Holgate


     

    C++ ARTICLES

    - Paths and Files
    - Directories in C++
    - Focusing on C++ Files
    - Const Correctness in C++
    - Manipulating Streams and Files with C++
    - Streams and Files
    - Multiplying Large Numbers with Karatsuba`s A...
    - Large Numbers
    - Dijkstra`s Shunting Algorithm with STL and C...
    - Brief Introduction to the STL Containers
    - The Standard Template Library
    - Templates in C++
    - C++ Programmer Alerts
    - C++ Programming Tips
    - First Steps in (C) Programming, conclusion






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT