| Tenouk | Home | Previous | Next | Download  |  Site Index  |  Disclaimer  |  Privacy | Contact | Tell friends |


 

 

C++, MFC, Winsock and WinInet Part 2

 

Program examples compiled using Visual C++ 6.0 compiler on Windows XP Pro machine with Service Pack 2 and some Figure screen snapshots have been taken on Windows 2000 server. Topics and sub topics for this tutorial are listed below. Don’t forget to read Tenouk’s small disclaimer.  Supplementary item is WEBSITE.

 

Index:
 
Winsock
Synchronous vs. Asynchronous Winsock Programming
The MFC Winsock Classes
The Blocking Socket Classes
The CSockAddr Helper Class
The CBlockingSocketException Class
The CBlockingSocket Class
The CHttpBlockingSocket Class
A Simplified HTTP Server Program
Initializing Winsock
Starting the Server
The Server Thread
Cleaning Up
A Simplified HTTP Client Program

 

 

 

 

Winsock

 

Winsock is the lowest level Windows API for TCP/IP programming. Part of the code is located in wsock32.dll (the exported functions that your program calls), and part is inside the Windows kernel. You can write both internet server programs and internet client programs using the Winsock API. This API is based on the original Berkeley Sockets API for UNIX. A new and much more complex version, Winsock 2, is included for the first time with Windows NT 4.0, but we'll stick with the old version because it's simplicity. The Winsock 2 has been discussed in module Winsock2.

 

Synchronous vs. Asynchronous Winsock Programming

 

Winsock was introduced first for Win16, which did not support multithreading. Consequently, most developers used Winsock in the asynchronous mode. In that mode, all sorts of hidden windows and PeekMessage() calls enabled single-threaded programs to make Winsock send and receive calls without blocking, thus keeping the user interface (UI) alive. Asynchronous Winsock programs were complex, often implementing "state machines" that processed callback functions, trying to figure out what to do next based on what had just happened. Well, we're not in 16-bit land anymore, so we can do modern multithreaded programming. If this scares you, go back and review Module 22. Once you get used to multithreaded programming, you'll love it.

In this module, we will make the most of our Winsock calls from worker threads so that the program's main thread is able to carry on with the UI. The worker threads contain nice, sequential logic consisting of blocking Winsock calls.

 

The MFC Winsock Classes

 

We try to use MFC classes where it makes sense to use them, but the MFC developers informed us that the CAsyncSocket and CSocket classes were not appropriate for 32-bit synchronous programming. The Visual C++ online help says you can use CSocket for synchronous programming, but if you look at the source code you'll see some ugly message-based code left over from Win16.

 

The Blocking Socket Classes

 

Since we couldn't use MFC, we had to write our own Winsock classes. CBlockingSocket is a thin wrapping of the Winsock API, designed only for synchronous use in a worker thread. The only fancy features are exception-throwing on errors and time-outs for sending and receiving data. The exceptions help you write cleaner code because you don't need to have error tests after every Winsock call. The time-outs (implemented with the Winsock select function) prevent a communication fault from blocking a thread indefinitely.

CHttpBlockingSocket is derived from CBlockingSocket and provides functions for reading HTTP data. CSockAddr and CBlockingSocketException are helper classes.

 

The CSockAddr Helper Class

 

Many Winsock functions take socket address parameters. As you might remember, a socket address consists of a 32-bit IP address plus a 16-bit port number. The actual Winsock type is a 16-byte sockaddr_in structure, which looks like this:

 

 

struct sockaddr_in {

    short   sin_family;

    u_short sin_port;

    struct  in_addr sin_addr;

    char    sin_zero[8];

};

 

The IP address is stored as type in_addr, which looks like this:

 

struct in_addr {

    union {

        struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;

        struct { u_short s_w1,s_w2; } S_un_w;

        u_long S_addr;

    } S_un;

}

 

These are ugly structures, so we'll derive a programmer-friendly C++ class from sockaddr_in. The file Blocksock.h contains the following code for doing this, with inline functions included:

 

class CSockAddr : public sockaddr_in {

public:

    // constructors

    CSockAddr()

    {

        sin_family = AF_INET;

        sin_port = 0;

        sin_addr.s_addr = 0;

    } // Default

    CSockAddr(const SOCKADDR& sa) { memcpy(this, &sa, sizeof(SOCKADDR)); }

    CSockAddr(const SOCKADDR_IN& sin) { memcpy(this, &sin, sizeof(SOCKADDR_IN)); }

    CSockAddr(const ULONG ulAddr, const USHORT ushPort = 0)

    // parms are host byte ordered

    {

        sin_family = AF_INET;

        sin_port = htons(ushPort);

        sin_addr.s_addr = htonl(ulAddr);

    }

    CSockAddr(const char* pchIP, const USHORT ushPort = 0) 

    // dotted IP addr string

    {

        sin_family = AF_INET;

        sin_port = htons(ushPort);

        sin_addr.s_addr = inet_addr(pchIP);

    } // already network byte ordered

    // Return the address in dotted-decimal format

    CString DottedDecimal()

        { return inet_ntoa(sin_addr); }

    // constructs a new CString object

    // Get port and address (even though they're public)

    USHORT Port() const

        { return ntohs(sin_port); }

    ULONG IPAddr() const

        { return ntohl(sin_addr.s_addr); }

    // operators added for efficiency

    const CSockAddr& operator=(const SOCKADDR& sa)

    {

        memcpy(this, &sa, sizeof(SOCKADDR));

        return *this;

    }

    const CSockAddr& operator=(const SOCKADDR_IN& sin)

    {

        memcpy(this, &sin, sizeof(SOCKADDR_IN));

        return *this;

    }

    operator SOCKADDR()

        { return *((LPSOCKADDR) this); }

    operator LPSOCKADDR()

        { return (LPSOCKADDR) this; }

    operator LPSOCKADDR_IN()

        { return (LPSOCKADDR_IN) this; }

};

 

As you can see, this class has some useful constructors and conversion operators, which make the CSockAddr object interchangeable with the type sockaddr_in and the equivalent types SOCKADDR_IN, sockaddr, and SOCKADDR. There's a constructor and a member function for IP addresses in dotted-decimal format. The internal socket address is in network byte order, but the member functions all use host byte order parameters and return values. The Winsock functions htonl, htons, ntohs, and ntohl take care of the conversions between network and host byte order.

 

The CBlockingSocketException Class

 

All the CBlockingSocket functions throw a CBlockingSocketException object when Winsock returns an error. This class is derived from the MFC CException class and thus overrides the GetErrorMessage() function. This function gives the Winsock error number and a character string that CBlockingSocket provided when it threw the exception.

 

The CBlockingSocket Class

 

Listing 1 shows an excerpt from the header file for the CBlockingSocket class.

 

BLOCKSOCK.H

 

class CBlockingSocket : public CObject

{

    DECLARE_DYNAMIC(CBlockingSocket)

public:

    SOCKET m_hSocket;

    CBlockingSocket();  { m_hSocket = NULL; }

    void Cleanup();

    void Create(int nType = SOCK_STREAM);

    void Close();

    void Bind(LPCSOCKADDR psa);

    void Listen();

    void Connect(LPCSOCKADDR psa);

    BOOL Accept(CBlockingSocket& s, LPCSOCKADDR psa);

    int Send(const char* pch, const int nSize, const int nSecs);

    int Write(const char* pch, const int nSize, const int nSecs);

    int Receive(char* pch, const int nSize, const int nSecs);

    int SendDatagram(const char* pch, const int nSize, LPCSOCKADDR psa,

        const int nSecs);

    int ReceiveDatagram(char* pch, const int nSize, LPCSOCKADDR psa,

        const int nSecs);

    void GetPeerAddr(LPCSOCKADDR psa);

    void GetSockAddr(LPCSOCKADDR psa);

    static CSockAddr GetHostByName(const char* pchName,

        const USHORT ushPort = 0);

    static const char* GetHostByAddr(LPCSOCKADDR psa);

    operator SOCKET();

        { return m_hSocket; }

};

 

Listing 1:  Excerpt from the header file for the CBlockingSocketclass.

 

Following is a list of the CBlockingSocket member functions, starting with the constructor:

 

          Constructor(): The CBlockingSocket constructor makes an uninitialized object. You must call the Create() member function to create a Windows socket and connect it to the C++ object.

          Create(): This function calls the Winsock socket function and then sets the m_hSocket data member to the returned 32-bit SOCKET handle.

 

Parameter

Description

nType

Type of socket; should be SOCK_STREAM (the default value) or SOCK_DGRAM.

 

Table 1.

 

          Close(): This function closes an open socket by calling the Winsock closesocket function. The Create() function must have been called previously. The destructor does not call this function because it would be impossible to catch an exception for a global object. Your server program can call Close() anytime for a socket that is listening.

          Bind(): This function calls the Winsock bind function to bind a previously created socket to a specified socket address. Prior to calling Listen(), your server program calls Bind() with a socket address containing the listening port number and server's IP address. If you supply INADDR_ANY as the IP address, Winsock deciphers your computer's IP address.

 

Parameter

Description

psa

A CSockAddr object or a pointer to a variable of type sockaddr.

 

Table 2.

 

          Listen(): This TCP function calls the Winsock listen function. Your server program calls Listen() to begin listening on the port specified by the previous Bind() call. The function returns immediately.

          Accept(): This TCP function calls the Winsock accept function. Your server program calls Accept() immediately after calling Listen(). Accept returns when a client connects to the socket, sending back a new socket (in a CBlockingSocket object that you provide) that corresponds to the new connection.

 

Parameter

Description

s

A reference to an existing CBlockingSocket object for which Create() has not been called.

psa

A CSockAddr object or a pointer to a variable of type sockaddr for the connecting socket's address.

Return value

TRUE if successful.

 

Table 3.

 

          Connect(): This TCP function calls the Winsock connect function. Your client program calls Connect() after calling Create(). Connect returns when the connection has been made.

 

Parameter

Description

psa

A CSockAddr object or a pointer to a variable of type sockaddr.

 

Table 4.

 

          Send(): This TCP function calls the Winsock send function after calling select to activate the time-out. The number of bytes actually transmitted by each Send() call depends on how quickly the program at the other end of the connection can receive the bytes. Send() throws an exception if the program at the other end closes the socket before it reads all the bytes.

 

Parameter

Description

pch

A pointer to a buffer that contains the bytes to send.

nSize

The size (in bytes) of the block to send.

nSecs

Time-out value in seconds.

Return value

The actual number of bytes sent.

 

Table 5.

 

          Write(): This TCP function calls Send() repeatedly until all the bytes are sent or until the receiver closes the socket.

 

Parameter

Description

pch

A pointer to a buffer that contains the bytes to send.

nSize

The size (in bytes) of the block to send.

nSecs

Time-out value in seconds.

Return value

The actual number of bytes sent.

 

Table 6.

 

          Receive(): This TCP function calls the Winsock recv function after calling select to activate the time-out. This function returns only the bytes that have been received. For more information, see the description of the CHttpBlockingSocket class in the next section.

 

Parameter

Description

pch

A pointer to an existing buffer that will receive the incoming bytes.

nSize

The maximum number of bytes to receive.

nSecs

Time-out value in seconds.

Return value

The actual number of bytes received.

 

Table 7.

 

          SendDatagram(): This UDP function calls the Winsock sendto() function. The program on the other end needs to call ReceiveDatagram(). There is no need to call Listen(), Accept(), or Connect() for datagrams. You must have previously called Create() with the parameter set to SOCK_DGRAM.

 

Parameter

Description

pch

A pointer to a buffer that contains the bytes to send.

nSize

The size (in bytes) of the block to send.

psa

The datagram's destination address; a CSockAddr object or a pointer to a variable of type sockaddr.

nSecs

Time-out value in seconds.

Return value

The actual number of bytes sent.

 

Table 8.

 

          ReceiveDatagram(): This UDP function calls the Winsock recvfrom() function. The function returns when the program at the other end of the connection calls SendDatagram(). You must have previously called Create() with the parameter set to SOCK_DGRAM.

 

Parameter

Description

pch

A pointer to an existing buffer that will receive the incoming bytes.

nSize

The size (in bytes) of the block to send.

psa

The datagram's destination address; a CSockAddr object or a pointer to a variable of type sockaddr.

nSecs

Time-out value in seconds.

Return value

The actual number of bytes received.

 

Table 9.

 

          GetPeerAddr(): This function calls the Winsock getpeername() function. It returns the port and IP address of the socket on the other end of the connection. If you are connected to the Internet through a Web proxy server, the IP address is the proxy server's IP address.

 

Parameter

Description

psa

A CSockAddr object or a pointer to a variable of type sockaddr.

 

Table 10.

 

          GetSockAddr(): This function calls the Winsock getsockname() function. It returns the socket address that Winsock assigns to this end of the connection. If the other program is a server on a LAN, the IP address is the address assigned to this computer's network board. If the other program is a server on the Internet, your service provider assigns the IP address when you dial in. In both cases, Winsock assigns the port number, which is different for each connection.

 

Parameter

Description

psa

A CSockAddr object or a pointer to a variable of type sockaddr.

 

Table 11.

 

          GetHostByName(): This static function calls the Winsock function gethostbyname(). It queries a name server and then returns the socket address corresponding to the host name. The function times out by itself.

 

Parameter

Description

pchName

A pointer to a character array containing the host name to resolve.

ushPort

The port number (default value 0) that will become part of the returned socket address.

Return value

The socket address containing the IP address from the DNS plus the port number ushPort.

 

Table 12.

 

          GetHostByAddr(): This static function calls the Winsock gethostbyaddr() function. It queries a name server and then returns the host name corresponding to the socket address. The function times out by itself.

 

Parameter

Description

psa

A CSockAddr object or a pointer to a variable of type sockaddr.

Return value

A pointer to a character array containing the host name; the caller should not delete this memory.

 

Table 13.

 

          Cleanup(): This function closes the socket if it is open. It doesn't throw an exception, so you can call it inside an exception catch block.

          Operator SOCKET: This overloaded operator lets you use a CBlockingSocket object in place of a SOCKET parameter.

 

The CHttpBlockingSocket Class

 

If you call CBlockingSocket::Receive, you'll have a difficult time knowing when to stop receiving bytes. Each call returns the bytes that are stacked up at your end of the connection at that instant. If there are no bytes, the call blocks, but if the sender closed the socket, the call returns zero bytes. In the HTTP section, you learned that the client sends a request terminated by a blank line. The server is supposed to send the response headers and data as soon as it detects the blank line, but the client needs to analyze the response headers before it reads the data. This means that as long as a TCP connection remains open, the receiving program must process the received data as it comes in. A simple but inefficient technique would be to call Receive() for 1 byte at a time. A better way is to use a buffer. The CHttpBlockingSocket class adds buffering to CBlockingSocket, and it provides two new member functions. Here is part of the Blocksock.h file:

 

class CHttpBlockingSocket : public CBlockingSocket

{

public:

    DECLARE_DYNAMIC(CHttpBlockingSocket)

    enum {nSizeRecv = 1000}; // max receive buffer size (> hdr line

                             //  length)

    CHttpBlockingSocket();

    ~CHttpBlockingSocket();

    int ReadHttpHeaderLine(char* pch, const int nSize, const int nSecs);

    int ReadHttpResponse(char* pch, const int nSize, const int nSecs);

private:

    char* m_pReadBuf; // read buffer

    int m_nReadBuf; // number of bytes in the read buffer

};

 

The constructor and destructor take care of allocating and freeing a 1000-character buffer. The two new member functions are as follows:

 

          ReadHttpHeaderLine(): This function returns a single header line, terminated with a <cr><lf> pair. ReadHttpHeaderLine() inserts a terminating zero at the end of the line. If the line buffer is full, the terminating zero is stored in the last position.

 

Parameter

Description

pch

A pointer to an existing buffer that will receive the incoming line (zero-terminated).

nSize

The size of the pch buffer.

nSecs

Time-out value in seconds.

Return value

The actual number of bytes received, excluding the terminating zero.

 

Table 14.

 

          ReadHttpResponse(): This function returns the remainder of the server's response received when the socket is closed or when the buffer is full. Don't assume that the buffer contains a terminating zero.

 

Parameter

Description

pch

A pointer to an existing buffer that will receive the incoming data.

nSize

The maximum number of bytes to receive.

nSecs

Time-out value in seconds.

Return value

The actual number of bytes received.

 

Table 15.

 

A Simplified HTTP Server Program

 

Now it's time to use the blocking socket classes to write an HTTP server program. All the frills have been eliminated, but the code actually works with a browser. This server doesn't do much except return some hard-coded headers and HTML statements in response to any GET request. (See the MYEX33A program later in this module for a more complete HTTP server.)

 

Initializing Winsock

 

Before making any Winsock calls, the program must initialize the Winsock library. The following statements in the application's InitInstance() member function do the job:

 

WSADATA wsd;

WSAStartup(0x0101, &wsd);

 

Starting the Server

 

The server starts in response to some user action, such as a menu choice. Here's the command handler:

 

CBlockingSocket g_sListen; // one-and-only global socket for listening

void CSocketView::OnInternetStartServer()

{

    try {

        CSockAddr saServer(INADDR_ANY, 80);

        g_sListen.Create();

        g_sListen.Bind(saServer);

        g_sListen.Listen();

        AfxBeginThread(ServerThreadProc, GetSafeHwnd());

    }

    catch(CBlockingSocketException* e) {

        g_sListen.Cleanup();

        // Do something about the exception

        e->Delete();

    }

}

 

Pretty simple, really. The handler creates a socket, starts listening on it, and then starts a worker thread that waits for some client to connect to port 80. If something goes wrong, an exception is thrown. The global g_sListen object lasts for the life of the program and is capable of accepting multiple simultaneous connections, each managed by a separate thread.

 

The Server Thread

 

Now let's look at the ServerThreadProc() function:

 

UINT ServerThreadProc(LPVOID pParam)

{

    CSockAddr saClient;

    CHttpBlockingSocket sConnect;

    char request[100];

    char headers[] = "HTTP/1.0 200 OK\r\n"

        "Server: Inside Visual C++ SOCK01\r\n"

        "Date: Thu, 05 Sep 2005 17:33:12 GMT\r\n"

        "Content-Type: text/html\r\n"

        "Accept-Ranges: bytes\r\n"

        "Content-Length: 187\r\n"