Windows MFC Example.cpp 2.82 KB
Newer Older
O'Reilly Media, Inc. committed
1
#include "stdafx.h"
#include <dns_sd.h>
#include <winsock2.h>

#define WM_PRIVATE_SERVICE_EVENT                ( WM_USER + 0x100 )

class MyWindow
:
    public CWnd
{
public:

    MyWindow();
    virtual ~MyWindow( void );

protected:

    // General

    afx_msg int     OnCreate( LPCREATESTRUCT inCreateStruct );
    afx_msg void    OnDestroy( void );
    afx_msg LONG    OnServiceEvent( WPARAM inWParam, LPARAM inLParam );

    // Browsing

    static void DNSSD_API
    BrowseReply(
            DNSServiceRef           inRef,
            DNSServiceFlags         inFlags,
            uint32_t                inInterfaceIndex,
            DNSServiceErrorType     inErrorCode,
            const char *            inName,
            const char *            inType,
            const char *            inDomain,
            void *                  inContext );

    DECLARE_MESSAGE_MAP()

private:

    DNSServiceRef m_serviceRef;
};

BEGIN_MESSAGE_MAP( MyWindow, CWnd )
    ON_WM_CREATE()
    ON_WM_DESTROY()
    ON_MESSAGE( WM_PRIVATE_SERVICE_EVENT, OnServiceEvent )
END_MESSAGE_MAP()

int
MyWindow::OnCreate( LPCREATESTRUCT inCreateStruct )
    {
    DNSServiceErrorType err;

    err = CWnd::OnCreate( inCreateStruct );

    if ( err )
        goto exit;

    err = DNSServiceBrowse( &m_serviceRef, 0, 0, "_http._tcp", NULL, BrowseReply, this );

    if ( err )
        goto exit;

    err = WSAAsyncSelect( (SOCKET) DNSServiceRefSockFD(m_serviceRef), m_hWnd,
                         WM_PRIVATE_SERVICE_EVENT, FD_READ|FD_CLOSE);

exit:

    if ( err )
        {
        if ( m_serviceRef )
            {
            DNSServiceRefDeallocate( m_serviceRef );
            m_serviceRef = NULL;
            }
        }

    return( err );
    }

void
MyWindow::OnDestroy( void )
    {
    // ...

    if ( m_serviceRef )
        {
        WSAAsyncSelect( ( SOCKET ) DNSServiceRefSockFD( m_serviceRef ), m_hWnd, 0, 0 );
        DNSServiceRefDeallocate( m_serviceRef );
        }

    // ...
    }

LONG
MyWindow::OnServiceEvent(WPARAM inWParam, LPARAM inLParam)
    {
    SOCKET              sock = (SOCKET) inWParam;
    DNSServiceErrorType err;

    if ( WSAGETSELECTERROR(inLParam) && !(HIWORD(inLParam)))
        goto exit;

    ASSERT( ( SOCKET ) DNSServiceRefSockFD( m_serviceRef ) == sock );
    err = DNSServiceProcessResult( m_serviceRef );
    ASSERT( !err );

exit:

    return ( 0 );
    }

void DNSSD_API
MyWindow::BrowseReply(
        DNSServiceRef           inRef,
        DNSServiceFlags         inFlags,
        uint32_t                inInterfaceIndex,
        DNSServiceErrorType     inErrorCode,
        const char *            inName,
        const char *            inType,
        const char *            inDomain,
        void *                  inContext )
    {
    MyWindow * self = reinterpret_cast<MyWindow*>( inContext );
    ASSERT( self );

    // ...
    }