第十三章 网络通信与因特网应用程序

Click here to load reader

download 第十三章  网络通信与因特网应用程序

of 208

description

第十三章 网络通信与因特网应用程序. 由于 因特网 的的出现和迅速盛行,基于 网络通信 ,越来越多 的应用程序的运行环境不再是 同地 的 单机 系统,而是通过网络 (包括局域网和因特网)连接起来的 异地 的 多机 系统。从 Windows NT 和 Windows 95 开始,微软把 网络功能 逐步地融入到 其操作系统之中,使得 网络功能 在各类应用程序中,根据功能 需要完成不同程度和不同需要的网络任务已不是新鲜话题。例 如,对一个 Web 站点中运行的应用程序进行核实,判断是否已 经更新,并提示用户是否更新程序版本;又如,网络游戏程序 - PowerPoint PPT Presentation

Transcript of 第十三章 网络通信与因特网应用程序

  • Windows NT Windows 95 Web

  • 13.1 Windows Winsock MFC CAsyncSocket CSocket Winsock Winsock MFC Winsock Winsock MFC Winsock MFC Winsock Winsock

  • 1 2 3

  • 4 5

  • TCP/IP UDP

  • 13.1.1 UNIX Windows 95 Windows WinSock Windows SocketAPI

  • Socket

  • 13.1.2 Visual C++ WinSock API MFC Winsock MFC WinsockCAsyncSocket 1 Windows Sockets stdafx.h #endif // _AFX_NO_AFXCMN_SUPPORT #include // MFC socket extensions //{{AFX_INSERT_LOCATION}}

  • InitInstance Windows Sockets BOOL CSockApp::InitInstance() { if (!AfxSocketInit()) {AfxMessageBox(IDP_SOCKETS_INIT_FAILED);return FALSE; } AfxEnableControlContainer(); }

  • 2 CAsyncSocket class CMyDlg : public CDialog { private:CAsyncSocket m_sMySocket; };

  • 3 Create Create Create if(m_sMySocket.Create())// Continue onelse// Perform error handling here

  • if(m_sMySocket.Create(4000))// Continue onelse// Perform error handling here Create

  • BOOL Create( UINT nSocketPort = 0, int nSocketType = SOCK_STREAM, long lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, LPCTSTR lpszSocketAddress = NULL ); nSocketPort Windows Sockets 0

  • nSocketTypeSOCK_STREAM TCP SOCK_DGRAM () UDP lEvent lpszSocketAddress128.56.22.8 0 0 GetLastError Create

  • WSANOTINITIALISEDA successful AfxSocketInit must occur before using this API. WSAENETDOWNThe Windows Sockets implementation detected that the network subsystem failed. WSAEAFNOSUPPORTThe specified address family is not supported. WSAEINPROGRESSA blocking Windows Sockets operation is in progress. WSAEMFILENo more file descriptors are available. WSAENOBUFSNo buffer space is available. The socket cannot be created.

  • WSAEPROTONOSUPPORTThe specified port is not supported. WSAEPROTOTYPEThe specified port is the wrong type for this socket. WSAESOCKTNOSUPPORTThe specified socket type is not supported in this address.

  • 13.1.3

  • 1 Listen Listen BOOL Listen( int nConnectionBacklog = 5 );nConnectionBacklog1 - 5 5 00GetLastError Listen

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.WSAEADDRINUSE An attempt has been made to listen on an address in use.WSAEINPROGRESSA blocking Windows Sockets operation is in progress.WSAEINVAL The socket has not been bound with Bind or is already connected.WSAEISCONNThe socket is already connected.

  • WSAEMFILE No more file descriptors are available.WSAENOBUFSNo buffer space is available.WSAENOTSOCK The descriptor is not a socket.WSAEOPNOTSUPP The referenced socket is not of a type that supports the Listen operation. if( m_sMySocket.Listen()) // Continue on else // Perform error handling here

  • 2 Connect Connect BOOL Connect( LPCTSTR lpszHostAddress, UINT nHostPort );BOOL Connect( const SOCKADDR* lpSockAddr, int nSockAddrLen );lpszHostAddressftp.microsoft.com, 128.56.22.8nHostPortlpSockAddr SOCKADDR nSockAddrLen SOCKADDR

  • 00GetLastError Connect WSANOTINITIALISEDA successful AfxSocketInit must occur before using this API.WSAENETDOWNThe Windows Sockets implementation detected that the network subsystem failed.WSAEADDRINUSEThe specified address is already in use.WSAEINPROGRESSA blocking Windows Sockets call is in progress.

  • WSAEADDRNOTAVAILThe specified address is not available from the local machine.WSAEAFNOSUPPORTAddresses in the specified family cannot be used with this socket.WSAECONNREFUSEDThe attempt to connect was rejected.WSAEDESTADDRREQA destination address is required.WSAEFAULTThe nSockAddrLen argument is incorrect.WSAEINVALInvalid host address.WSAEISCONNThe socket is already connected.WSAEMFILENo more file descriptors are available.WSAENETUNREACHThe network cannot be reached from this host at this time.

  • WSAENOBUFSNo buffer space is available. The socket cannot be connected.WSAENOTSOCKThe descriptor is not a socket.WSAETIMEDOUTAttempt to connect timed out without establishing a connection.WSAEWOULDBLOCKThe socket is marked as nonblocking and the connection cannot be completed immediately.

  • Connect if(m_sMySocket.Connect(thatcomputer.com, 4000)) // Continue on else // Perform error handling here if(m_sMySocket.Connect(178.1.25.82, 4000)) // Continue on else // Perform error handling here

  • 3 Accept CAsyncSocket Create Accept Accept virtual BOOL Accept( CAsyncSocket& rConnectedSocket, SOCKADDR* lpSockAddr = NULL, int* lpSockAddrLen = NULL );

  • rConnectedSocket lpSockAddrSOCKADDR lpSockAddr /lpSockAddrLen NULLlpSockAddrLen SOCKADDR lpSockAddr

  • Accept if(m_sMySocket.Accept(m_sMySecondSocket)) // Continue on else // Perform error handling here m_sMySecondSocket

  • 13.1.4 CString Send virtual int Send( const void* lpBuf, int nBufLen, int nFlags = 0 );lpBufnBufLen

  • nFlags nFlagsMSG_DONTROUTEWindows MSG_OOB SOCK_STREAM SOCKET_ERROR GetLastError

  • WSANOTINITIALISEDA successful AfxSocketInit must occur before using this API.WSAENETDOWNThe Windows Sockets implementation detected that the network subsystem failed.WSAEACCESThe requested address is a broadcast address, but the appropriate flag was not set.WSAEINPROGRESSA blocking Windows Sockets operation is in progress.WSAEFAULTThe lpBuf argument is not in a valid part of the user address space.WSAENETRESETThe connection must be reset because the Windows Sockets implementation dropped it.WSAENOBUFSThe Windows Sockets implementation reports a buffer deadlock.

  • WSAENOTCONNThe socket is not connected.WSAENOTSOCKThe descriptor is not a socket.WSAEOPNOTSUPPMSG_OOB was specified, but the socket is not of type SOCK_STREAM.WSAESHUTDOWNThe socket has been shut down; it is not possible to call Send on a socket after ShutDown has been invoked with nHow set to 1 or 2.WSAEWOULDBLOCKThe socket is marked as nonblocking and the requested operation would block.WSAEMSGSIZEThe socket is of type SOCK_DGRAM, and the datagram is larger than the maximum supported by the Windows Sockets implementation.

  • WSAEINVALThe socket has not been bound with Bind.WSAECONNABORTEDThe virtual circuit was aborted due to timeout or other failure.WSAECONNRESETThe virtual circuit was reset by the remote side.

  • Send CString strMyMessage; int iLen; int iAmtSent; iLen = strMyMessage.GetLength(); iAmtSent = m_sMySocket.Send((LPCTSTR(strMyMessage), iLen); if(iAmtSent == SOCKET_ERROR) // Do some error handling here else // Everythings fine

  • Receive Receive virtual int Receive( void* lpBuf, int nBufLen, int nFlags = 0 );lpBufnBufLennFlagsnFlagsMSG_PEEKMSG_OOB

  • 0 SOCKET_ERROR GetLastErrorWSANOTINITIALISEDA successful AfxSocketInit must occur before using this API.WSAENETDOWNThe Windows Sockets implementation detected that the network subsystem failed.WSAENOTCONNThe socket is not connected.WSAEINPROGRESSA blocking Windows Sockets operation is in progress.WSAENOTSOCKThe descriptor is not a socket.

  • WSAEOPNOTSUPPMSG_OOB was specified, but the socket is not of type SOCK_STREAM.WSAESHUTDOWNThe socket has been shut down; it is not possible to call Receive on a socket after ShutDown has been invoked with nHow set to 0 or 2.WSAEWOULDBLOCKThe socket is marked as nonblocking and the Receive operation would block.WSAEMSGSIZEThe datagram was too large to fit into the specified buffer and was truncated.WSAEINVALThe socket has not been bound with Bind.WSAECONNABORTEDThe virtual circuit was aborted due to timeout or other failure.WSAECONNRESETThe virtual circuit was reset by the remote side.

  • Receive char *pBuf = new char[1025]; int iBufSize = 1024; int iRcvd; CString strRecvd; iRcvd = m_sMySocket.Receive(pBuf, iBufsize); if(iRcvd == SOCKET_ERROR) // Do some error handling here else { pBuf[iRcvd] = NULL; strRecvd = pBuf; // Continue processing the messge }

  • 13.1.5 Close Closevirtual void Close( ); m_sMySocket.Close(); Close CAsyncSocket

  • 13.1.6 CAsyncSocket CAsyncSocket CAsyncSocket

  • OnAccept Accept OnCloseOnConnectOnReceive Receive OnSend Send

  • 13.1.7 CAsyncSocket FALSE Send Receive SOCKET_ERROR GetLastError int iErrCode; iErrCode = m_sMySocket.GetLastError(); switch(iErrCode) {

  • case WASNOTINITIALISED:AfxMessageBox(Windows socket has not be initialized.);break; case WSAENETDOWNAfxMessageBox(The network subsystem failed.);break; }

  • 13.2 WinSock

  • 13.2.1 AppWizard Sock Dialog Based Windows Winsock Visual C++ 6.0

  • Visual C++ .NET

  • 13.2.2 /

  • Group BoxIDCaptionIDC_STATICTYPESocket TypeRadio ButtonIDCaptionGroupIDC_RCLIENT&ClientCheckedRadio ButtonIDCaptionIDC_RSERVER&ServerStatic TextIDCaptionIDC_STATICNAMEServer &Name:Edit BoxIDIDC_ESERVNAMEStatic TextIDCaptionIDC_STATICPORTServer &Port:Edit BoxIDIDC_ESERVPORTButtonIDCaptionIDC_BCONNECTC&onnect

  • ButtonIDCaptionDisabledIDC_BCLOSEC&loseCheckedStatic TextIDCaptionDisabledIDC_STATICMSG&Message:CheckedEdit BoxIDDisabledIDC_EMSGCheckedButtonIDCaptionDisabledIDC_BSENDS&endCheckedStatic TextIDCaptionIDC_STATICSent:List BoxIDTab StopSortSelectionIDC_LSENTUncheckedUncheckedNoneStatic TextIDCaptionIDC_STATICReceived:List BoxIDTab StopSortSelectionIDC_LSENTUncheckedUncheckedNone

  • CSockDlg ClassWizard

    IDC_BCONNECTm_ctrlConnectCButton/IDC_EMSGm_strMessageCStringIDC_ESERVNAMEm_strNameCStringIDC_ESERVPORTm_iPortIntIDC_LRECVDm_ctrlRecvdCListBoxIDC_LSENTm_ctrlSentCListBoxIDC_RCLIENTm_iTypeint

  • Connect ClassWizard IDC_RCLIENT IDC_RSERVER BN_CLICKED OnRType

  • void CSockDlg::OnRType() { // TODO: Add your control notification handler code here // Sync the controls with variables UpdateData(TRUE); // Which mode are we in? if(m_iType == 0)// Set the appropriate text on the button m_ctrlConnect.SetWindowText("C&onnect"); else m_ctrlConnect.SetWindowText("&Listen");}

  • 13.2.3 CAsyncSocket CAsyncSocket CMySocket ClassWizard CMySocket CMySocket CSockDlg

  • 1 CMySocket CSockDlg CMySocket CSockDlg ) CDialog m_pWnd CSockDlg CMySocket SetParent( CDialog* pWnd )void CMySocket::SetParent(CDialog *pWnd){ // Set the member pointer m_pWnd = pWnd;}

  • 2 CMySocket CSockDlg OnAccept CMySocket CAsyncSocket OnAcceptvoid CMySocket::OnAccept(int nErrorCode) { // TODO: Add your specialized code here and/or call the base class // Were there any errors? if(nErrorCode == 0) // No, Call the dialog's OnAccept function ((CSockDlg*)m_pWnd)->OnAccept(); CAsyncSocket::OnAccept(nErrorCode);}

  • CSockDlg CSockDlg CMySocket OnAccept CMySocket OnConnectOnClose OnReceive OnAccept 3 CSockDlg CSockDlg CMySocket m_sConnectSocket m_sListenSocket

  • 4 CSockDlg OnInitDialog client loopbackTCP/IP localhost 127.0.0.1 4000 m_pWnd CSockDlg

  • OnInitDialog BOOL CSockDlg::OnInitDialog(){ CDialog::OnInitDialog(); // Initialize the control variables m_iType = 0;// Set socket as client m_strName = "loopback";// Set default name of server socket m_iPort = 4000; UpdateData(FALSE); // Update the controls // Set the socket dialog pointers m_sConnectSocket.SetParent(this); m_sListenSocket.SetParent(this); return TRUE; // return TRUE unless you set the focus to a control}

  • 13.2.4 Connect CSockDlg Connect BN_CLICKED OnBConnect Connect / Listen

  • void CSockDlg::OnBconnect() { // TODO: Add your control notification handler code here // Sync the variables with the controls UpdateData(TRUE); if(m_iType == 0) // Are we running as client or server? { m_sConnectSocket.Create(); // Client, create a default socket // Open the connection to the server if(m_sConnectSocket.Connect(m_strName, m_iPort) == 0 &&m_strName != "loopback" && m_strName != "localhost") {ErrorMessage(m_sConnectSocket.GetLastError());m_sConnectSocket.Close();return; } }

  • else { // Server, create a socket bound to the port specified m_sListenSocket.Create(m_iPort); if(m_sListenSocket.Listen() == 0) // Listen for connection requests {ErrorMessage(m_sListenSocket.GetLastError());m_sListenSocket.Close();return; } } // Disable the connection and type controls GetDlgItem (IDC_BCONNECT)->EnableWindow (FALSE); GetDlgItem (IDC_ESERVNAME)->EnableWindow (FALSE); GetDlgItem (IDC_ESERVPORT)->EnableWindow (FALSE);

  • GetDlgItem (IDC_STATICNAME)->EnableWindow (FALSE); GetDlgItem (IDC_STATICPORT)->EnableWindow (FALSE); GetDlgItem (IDC_RCLIENT)->EnableWindow (FALSE); GetDlgItem (IDC_RSERVER)->EnableWindow (FALSE); GetDlgItem (IDC_STATICTYPE)->EnableWindow (FALSE);}void CSockDlg::ErrorMessage(int errorCode){ CString errorStr; switch(errorCode) {

  • case WSANOTINITIALISED: errorStr = _T("A successful AfxSocketInit must occur before using this API."); break; case WSAENETDOWN: errorStr = _T("The Windows Sockets implementation detected that the \ network subsystem failed."); break; case WSAEAFNOSUPPORT: errorStr = _T("The specified address family is not supported."); break; case WSAEINPROGRESS: errorStr = _T("A blocking Windows Sockets operation is in progress."); break;

  • case WSAEMFILE: errorStr = _T("No more file descriptors are available."); break; case WSAENOBUFS: errorStr = _T("No buffer space is available. The socket cannot be created."); break; case WSAEPROTONOSUPPORT: errorStr = _T("The specified port is not supported."); break; case WSAEPROTOTYPE: errorStr = _T("The specified port is the wrong type for this socket."); break; case WSAESOCKTNOSUPPORT: errorStr = _T("The specified socket type is not supported in this address."); break;

  • case WSAEADDRINUSE: errorStr =_T("An attempt has been made to listen on an address in use."); break; case WSAEINVAL: errorStr = _T("The socket has not been bound with Bind or is already \ connected."); break; case WSAEISCONN: errorStr = _T("The socket is already connected."); break; case WSAENOTSOCK: errorStr = _T("The descriptor is not a socket."); break;

  • case WSAEOPNOTSUPP: errorStr =_T("The referenced socket is not of a type that supports the \ Listen operation."); break; case WSAEADDRNOTAVAIL: errorStr = _T("The specified address is not available from the local \machine."); break; case WSAECONNREFUSED: errorStr = _T("The attempt to connect was rejected."); break; case WSAEDESTADDRREQ: errorStr = _T("A destination address is required."); break;

  • case WSAEFAULT: errorStr = _T("The nSockAddrLen argument is incorrect."); break; case WSAENETUNREACH: errorStr = _T("The network cannot be reached from this host at this time."); break; case WSAETIMEDOUT: errorStr = _T("Attempt to connect timed out without establishing a \ connection."); break; case WSAEWOULDBLOCK: errorStr = _T("The socket is marked as nonblocking and the connection cannot be completed immediately."); break;

  • case WSAEACCES: errorStr =_T("The requested address is a broadcast address, but the \appropriate flag was not set."); break; case WSAENETRESET: errorStr = _T("The connection must be reset because the Windows \Sockets implementation dropped it."); break; case WSAESHUTDOWN: errorStr = _T("The socket has been shut down."); break; case WSAEMSGSIZE: errorStr = _T("The datagram is larger than the maximum supported \ by the Windows Sockets implementation."); break;

  • case WSAECONNABORTED: errorStr = _T("The virtual circuit was aborted due to timeout or other \failure."); break; case WSAECONNRESET: errorStr = _T("The virtual circuit was reset by the remote side."); break; case WSAENOTCONN: errorStr = _T("The socket is not connected."); break; } AfxMessageBox(errorStr);}

  • CSockDlg OnAcceptOnConnectOnAccept Accept

  • void CSockDlg::OnAccept(){ // Accept the Connection request if(m_sListenSocket.Accept(m_sConnectSocket)) { // Enable the text and message controls GetDlgItem (IDC_EMSG)->EnableWindow (TRUE); GetDlgItem (IDC_BSEND)->EnableWindow (TRUE); GetDlgItem (IDC_STATICMSG)->EnableWindow (TRUE); GetDlgItem (IDC_EMSG)->SetWindowText (_T("")); m_ctrlSent.ResetContent(); m_ctrlRecvd.ResetContent(); }}

  • void CSockDlg::OnConnect(){ // Enable the text and message controls GetDlgItem (IDC_EMSG)->EnableWindow (TRUE); GetDlgItem (IDC_BSEND)->EnableWindow (TRUE); GetDlgItem (IDC_STATICMSG)->EnableWindow (TRUE); GetDlgItem (IDC_BCLOSE)->EnableWindow (TRUE); GetDlgItem (IDC_EMSG)->SetWindowText (_T("")); m_ctrlSent.ResetContent(); m_ctrlRecvd.ResetContent();}

  • 13.2.5 Send CSockDlg Send BN_CLICKED OnBSend Send

  • void CSockDlg::OnBsend() { // TODO: Add your control notification handler code here int iLen; int iSent; // Sync the controls with the variables UpdateData(TRUE); // Is there a message to be sent? if(m_strMessage != "") { // Get the length of the message iLen = m_strMessage.GetLength(); // Send the message iSent=m_sConnectSocket.Send(LPCTSTR(m_strMessage), 2*iLen);

  • // Were we able to send it? if(iSent == SOCKET_ERROR)ErrorMessage(m_sConnectSocket.GetLastErroe()); else {// Add the message to the list box.m_ctrlSent.AddString(m_strMessage);// Sync the variables with the controlsUpdateData(FALSE); } }}

  • OnReceive Receive CString CSockDlg OnReceive CMySocket OnReceive void CSockDlg::OnReceive(){ TCHAR Buf[1025]; int iBufSize = 1024; int iRcvd; CString strRecvd;

  • // Receive the message iRcvd = m_sConnectSocket.Receive(Buf, iBufSize); if(iRcvd == SOCKET_ERROR) // Did we receive anything?ErrorMessage(m_sConnectSocket.GetLastErroe()); else {Buf[ iRcvd/2 ] = 0; // Truncate the end of the messagestrRecvd = Buf; // Copy the message to a CStringm_ctrlRecvd.AddString(strRecvd);// Add the message to the received list boxUpdateData(FALSE);// Sync the variables with the controls }}

  • 13.2.6 Close OnClose ( )

  • Close Send

    CSockDlg OnClose

  • void CSockDlg::OnClose(){ // Close the connected socket m_sConnectSocket.Close(); // Disable the message sending controls GetDlgItem (IDC_EMSG)->EnableWindow (FALSE); GetDlgItem (IDC_BSEND)->EnableWindow (FALSE); GetDlgItem (IDC_STATICMSG)->EnableWindow (FALSE); GetDlgItem (IDC_BCLOSE)->EnableWindow (FALSE); // Are we running in client mode if(m_iType == 0) {

  • // Yes, so anable the connection configuration controls GetDlgItem (IDC_BCONNECT)->EnableWindow (TRUE); GetDlgItem (IDC_ESERVNAME)->EnableWindow (TRUE); GetDlgItem (IDC_ESERVPORT)->EnableWindow (TRUE); GetDlgItem (IDC_STATICNAME)->EnableWindow (TRUE); GetDlgItem (IDC_STATICPORT)->EnableWindow (TRUE); GetDlgItem (IDC_RCLIENT)->EnableWindow (TRUE); GetDlgItem (IDC_RSERVER)->EnableWindow (TRUE); GetDlgItem (IDC_STATICTYPE)->EnableWindow (TRUE); }}

  • OnClose CMySocket Close BN_CLICKED OnBClosevoid CSockDlg::OnBclose() { // TODO: Add your control notification handler code here // Call the OnClose function OnClose();}

  • Sock 4000 3000

  • 3000

  • MFC WinSock CSocket CAsyncSocket CAsyncSocket CSocketFile CArchive CSocket CArchive ReceiveSendReceiveFromSendTo AcceptWSAEWOULDBLOCK CSocket::CancelBlockingCall WSAEINTR

  • WinSock API Ws2_32.dll WinSock API MFC WinSock WinSock API SDK API WSAStartup Ws2_32.dll WinSock API SDK API WSACleanup Ws2_32.dll NetPing WinSock API ping

  • 13.3 Internet Internet IntranetWindows Windows 2000 Windows XP

  • WinSock MFC WinSock Windows CGICommon Gateway Interface ISAPIInternet Server Application Interface WinInet MFC C(Client)-S(Server) B(Browser)-S(Server) B-S - Internet Intranet B-S

  • WWW Server runningyour ISAPI Serverextensions and filtersAdd http, ftp, andgopher supportusing WinInetAsynchronousMoniker transferInformation withoutblockingInternetWWW Client running aWeb Browser, displayingActive documents andActiveX controls

  • MFC 1 AfxParseURL URL CInternetSession::OpenURL AfxGetInternetHandleType

    2 ActiveX COleControl CObject

  • 3 CDocObjectServer CObject
  • 4 Moniker CAsyncMonikerFilter CObject
  • 5 ISAPI CHttpServer ISAPI Http CHttpServerContext CHttpServer Http Http CHttpFilter CHttpFilterContext CHttpFilter CHtmlStream HTML

  • 6 WinInet CInternetSession CObject Internet CInternetConnection CObject CFtpConnection CInternetConnection FTP Internet CGopherConnection CInternetConnection Gopher Internet

  • CHttpConnection CInternetConnection HTTP Internet CInternetFile CObject
  • CFtpFileFind CFileFind FTP CGopherFileFind CFileFind Gopher CGopherLocator CObject Gopher CGopherFileFind CInternetExcption CObject
  • MFC B-S ISAPI Visual C++ NET IE Web ATL Server Web ATL Server Web Web

  • 13.3.1 Web Web Navigator Netscape Microsoft Internet Explorer Web Internet Web

  • 13.3.1.1 CHtmlView CHtmlView Web Visual C++ 6.0 Visual C++ NET CHtmlView CFormView Web CHtmlView Web CHtmlView

  • GoBackGoForwardGoHomeGoSearchNavigateNavigate2RefreshRefresh2Stop

    PutProptyGetProptyExecWB URL URL , URL URL

  • 13.3.1.2 Web 1 HtmlBrowser CHtmlView CHtmlBrowserView

  • 2 CHtmlBrowserView OnInitUpdate() Web void CHtmlBrowserView::OnInitialUpdate() { CHtmlView::OnInitialUpdate(); Navigate2(_T( http://www.msdn.microsoft.com/visualc/ "), NULL, NULL); } Navigate2

  • 3 IDD_DIALOGBAR

    ID

    IDIDC_STATICCStatic IDC_EDIT_ADDRESSCEditIDC_BUTTON_GOCButtonIDC_BUTTON_NEXTCButtonIDC_BUTTON_BACKCButtonIDC_BUTTON_STOPCButton

  • 4 CMainFrame CDialogBar m_MyDialogBar CMainFrame::OnCreate if(!m_MyDialogBar.Create(this, IDD_DIALOGBAR, CBRS_TOP | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_HIDE_INPLACE, IDD_DIALOGBAR)){TRACE0("Failed to create dialog bar\n");return -1;// fail to create} m_MyDialogBar.EnableDocking(CBRS_ALIGN_TOP | CBRS_ALIGN_BOTTOM);DockControlBar(&m_MyDialogBar);

  • 5 m_MyDialogBar CMainFrame WM_SIZE m_bInit false WM_SIZE OnSize void CMainFrame::OnSize(UINT nType, int cx, int cy) {CFrameWnd::OnSize(nType, cx, cy);if(!m_bInit && m_MyDialogBar.GetSafeHwnd() && m_wndToolBar.GetSafeHwnd())

  • {m_bInit = TRUE;CRect rect, rect1;m_wndToolBar.GetWindowRect(&rect);m_MyDialogBar.GetWindowRect(&rect1);rect1 += CSize(rect.Width(), -rect.Height());DockControlBar(&m_MyDialogBar, AFX_IDW_DOCKBAR_TOP, &rect1); } }

  • 6 CMainFrame GetEditText void CMainFrame::GetEditText(CString& str){CEdit* pAddress = (CEdit*)m_MyDialogBar.GetDlgItem(IDC_EDIT_ADDRESS);pAddress->GetWindowText(str);}

  • 7 HtmlBrowserView.cpp #include MainFrm.h CHtmlBrowserView ON_BN_CLICKED(IDC_BUTTON_GO, &CHtmlBrowserView::OnButtonGo)ON_BN_CLICKED(IDC_BUTTON_NEXT, &CHtmlBrowserView::OnButtonNext)ON_BN_CLICKED(IDC_BUTTON_BACK, &CHtmlBrowserView::OnButtonBack)ON_BN_CLICKED(IDC_BUTTON_STOP, &CHtmlBrowserView::OnButtonStop)

  • void CHtmlBrowserView::OnButtonGo(){ CString str; ((CMainFrame*)(AfxGetApp()->GetMainWnd()))->GetEditText(str); Navigate2(str, NULL, NULL);}void CHtmlBrowserView::OnButtonNext(){ GoForward(); }void CHtmlBrowserView::OnButtonBack(){ GoBack(); }void CHtmlBrowserView::OnButtonStop(){ Stop();}

  • 8 HtmlBrowserhttp://www.msdn.microsoft.com/visualc/

  • 13.3.2 Web Web Web Web URL Windows Web CGI ISAPI ASPActive Server Pages ATL Server ATL Server

  • CGI1 2 HTML1 2 ISAPI1 2 3 HTML1 2 HTML ASP1 2 3 HTML1 2 ATL Server1 2 3 HTML4 5 HTML 1

  • 13.3.2.1 ATL Server ATL Server ISAPI

    IISISAPI DLLWeb DLL .srf

  • 1 SRF SRF Server Response File Web http:////SRF HTML Web Web Web Web DLL Web

  • Web SRF SRF Web

  • 2 IIS IIS Internet Information Services Web Web Web Web IIS Web Apache Iplanet IIS ATL Server

  • 3 ISAPI DLLISAPI DLL ATL Server ISAPI ISAPI DLL ISAPI DLL ATL Server SRF ATL Server DLL IIS IIS ISAPI DLL HttpExtensionProc EXTENSION_CONTROL_BLOCK ISAPI DLL HTTP

  • 4 ATL Server DLL ATL Server ATL Server DLL DLL SRF C++ HTML Request Handler Class CRequestHandlerT CRequestHandlerT COM IPplacementHandler HTML HTTP HTTP IPplacementHandler

  • ATL Server SRF HTML HTML Creator Template ISAPI SRF ATL Server DLL Web

  • 13.3.2.2 1 Windows NT 4 Windows 2000 SP 2 Windows XP Professional2 IIS IIS web 5.0 3 Internet Explorer 5.0

  • 13.3.2.2 Web 1 ATL Server MyATLServer

  • ATL Server Project Wizard Developer Support Options Attributed code

  • 2 ATL Server ATL Server ATL Server DLL ATL Server DLL .SRF MyATLServer CMyATLServerHandler

  • ISAPI DLL Web Internet DLL Web DLL SRF Web C:\Inetpub\wwwroot\\

  • Web SRF Build Rebuild Solution

  • 3 Web Visual C++ Debug Start Without Debugging

  • Web

  • 4 Web ATL Server MyATLServer SRF MyATLServer.h protected:// Here is an example of how to use a replacement tag with the // stencil processor[ tag_name(name="Hello") ]HTTP_CODE OnHello(void){m_HttpResponse
  • Visual C++ .NET SRF [tag_name(name=Hello)] tag_name SRF {{Hello}} OnHello m_HttpResponse CRequestHandlerT CHttpResponse m_HttpResponse HTTP_CODE DWORD HTTP_SUCCESS atlserr.h

  • .SRF MyATLServer.srf {{// use MSDN's "ATL Server Response File Reference" to learn about SRF files.}}{{handler MyATLServer.dll/Default}}This is a test: {{Hello}} {{// use MSDNs }} Web DLL HTML

  • {{handler MyATLServer.dll/Default}} SRF handler Web DLL MyATLServer.dll SRF SRF /DefaultWeb CMyATLServerHandler {{Hello}} SRF SRF if/else while

  • 5 Web Web Web Web SRF {{handler MyATLServer.dll/Default}}{{if Inputed}} = {{Name}} = {{Sex}} = {{Age}} = {{Adr}}

  • {{else}} {{endif}}

  • CMyATLServerHandler private: bool m_bInputed;// CString m_szUser;// CString m_age;// CString m_sex;// CString m_adr;// CMyATLServerHandler::ValidateAndExchange HTTP_CODE ValidateAndExchange() {m_HttpResponse.SetContentType("text/html");

  • // const CHttpRequestParams& FormFields = m_HttpRequest.GetFormVars();// input m_szUser = FormFields.Lookup("name");m_sex = FormFields.Lookup("sex");m_age = FormFields.Lookup("age");m_adr = FormFields.Lookup("adr");// ,if(m_szUser=="" && m_sex == "" && m_age == "" && m_adr == "")m_bInputed = false;elsem_bInputed = true;return HTTP_SUCCESS; }

  • ValidateAndExchange HTTP_CODE ValidateAndExchange() {m_HttpResponse.SetContentType("text/html");// const CHttpRequestParams& FormFields = m_HttpRequest.GetFormVars();// input CValidateContext valCtx;m_HttpRequest.FormVars.Exchange("name",&m_szUser,&valCtx);m_HttpRequest.FormVars.Exchange("sex", &m_sex, &valCtx);m_HttpRequest.FormVars.Exchange("age", &m_age, &valCtx);m_HttpRequest.FormVars.Exchange("adr", &m_adr, &valCtx);

  • // ,if(m_szUser == "" && m_sex == "" && m_age == "" && m_adr == "")m_bInputed = false;elsem_bInputed = true;return HTTP_SUCCESS; }

  • CMyATLServerHandler [ tag_name(name = "Inputed")]HTTP_CODE OnInputed(void){ if(m_bInputed)return HTTP_SUCCESS; elsereturn HTTP_S_FALSE;}

  • [ tag_name(name = "Name")]HTTP_CODE OnName(void){ m_HttpResponse
  • [ tag_name(name = "Age")]HTTP_CODE OnAge(void){ m_HttpResponse
  • 6 Web Web Build Rebuild Solution ATL Server Debug Start Without Debugging Web

  • 13.3.3 Web Internet Internet

  • 13.3.3.1 Web 1 Web Web Web XML Internet Web Web XML Web

  • Web Web Web Web Web Web Windows Web Web

  • 2 Web ActiveX ActiveX Web ActiveX ActiveX ActiveX ActiveX Web Web URL URL XML

  • 3 Web Web Web Web ATL Server Web SOAPWeb SOAP Visual Studio SOAP Web tag_name .SRF Web soap_method Hello World Web Web

  • [ tag_name(name = Hello)]// Web HTTP_CODE OnHello(void){m_HttpResponse
  • Web .SRF DLL Web .htm DLL Web Web .DISCO Web Web

  • 4 XML (Extensible Markup Language) XML 1996 W3C XML HTML HTML XML XML XML XML Web XML SOAP Web XML Web XML Web XML

  • Simple XML August 6, 2003 Su Fari XML is pretty easy . In this chapter, we present a wide variety of examplesthat use XML .

  • XML XML version XML XML XML Tag XML XML

  • XML

  • SOAPSimple Object Access Protocal SOAP XML Web SOAP XML SOAP SOAP HTTP FTPSMTP SOAP SOAP

  • UDDIUniversal Description, Discovery, and Integration UDDI Web Web Internet Web UDDI Web Web UDDI DISCO DISCO UDDI Web Internet Web DISCO XML

  • 13.3.3.2 Web Web Windows DCOM Distributed Component Object Model UNIX CORBA Common Object Request Broker Architecture

  • 1 Web Web HTTP SOAP HTTP Internet SOAP HTTP SOAP XML Web Web RPC Remote Procedure Call DCOM IIOPInternet Inter ORB Protocol CORBA

  • 2 Web COM Internet COM Web HTTP 80 Web Web 3 Web .NET Visual Studio ATL Server Web

  • 13.3.3.3 Web Web Web Web Web Web Web Visual Studio .NET Web Web

  • 1 ATL Server Web FileNew Project New Project ATL Server Web Service TempConvert4

  • OK ATL Server Project Wizard

    Finish ISAPI Web

  • 2 Web Web ISAPI Web ISAPI IIS ISAPI .disco Web Web Web Add Web Reference

  • .htm XML Web Web SOAP Web TempConver4.h XML TempConver4.h TempConver4.cpp TempConver4.h

  • // TempConvert4.h : Defines the ATL Server request handler class#pragma oncenamespace TempConvert4Service{ // all struct, enum, and typedefs for your webservice should go inside // the namespace// ITempConvert4Service - web service interface declaration[ uuid("7A6BEBF4-403F-4E86-94AF-A473F2B39A1F"), object ]__interface ITempConvert4Service{// HelloWorld is a sample ATL Server web service method. // It shows how to declare a web service method and // its in-parameters and out-parameters[id(1)] HRESULT HelloWorld([in] BSTR bstrInput, [out, retval] BSTR *bstrOutput);// TODO: Add additional web service methods here};

  • // TempConvert4Service - web service implementation[request_handler(name="Default", sdl="GenTempConvert4WSDL"),soap_handler( name="TempConvert4Service", namespace="urn:TempConvert4Service", protocol="soap )]

    class CTempConvert4Service : public ITempConvert4Service{public:// This is a sample web service method that shows how to use the // soap_method attribute to expose a method as a web method

  • [ soap_method ]HRESULT HelloWorld(/*[in]*/ BSTR bstrInput, /*[out, retval]*/ BSTR *bstrOutput){CComBSTR bstrOut(L"Hello ");bstrOut += bstrInput;bstrOut += L"!";*bstrOutput = bstrOut.Detach();return S_OK;}// TODO: Add additional web service methods here}; // class CTempConvert4Service} // namespace TempConvert4Service

  • TempConvert4Service Web Web HelloWorld Web request_handler Web HTTP SOAP name name=Default sdl sdl = GenTempConvert4WSDL

  • soap_handler SOAP name Web namespace XML protocol Web soap Web soap_method SOAP HelloWorld

  • 3 Web Web Web ConvertF2C ConvertC2F __interface ITempConvert4Service {[id(1)] HRESULT HelloWorld([in] BSTR bstrInput, [out, retval] BSTR *bstrOutput);// TODO: Add additional web service methods here[id(1)] HRESULT ConvertF2C([in] double dFahrenheit, [out, retval] double* pdCelsius);[id(1)] HRESULT ConvertC2F([in] double dCelsius, [out, retval] double* pdFahrenheit); };

  • Web // TODO: Add additional web service methods here [ soap_method ] HRESULT ConvertF2C(double dFahrenheit, double* pdCelsius) {if(!pdCelsius) return E_INVALIDARG;*pdCelsius = ((dFahrenheit - 32) * 5) / 9;return S_OK; } [ soap_method ] HRESULT ConvertC2F(double dCelsius, double* pdFahrenheit) {if(!pdFahrenheit) return E_INVALIDARG;*pdFahrenheit = dCelsius * 9 / 5 + 32;return S_OK; }

  • TempConvert4.htm ConvertF2C ConvertC2F HelloWorld The following operations are supported. For a formal definition, please review the Service Description.HelloWorld ConvertF2C ConvertC2F

  • 4 Web Web ISAPI DLL Build Build Solution Web Build Rebuild Solution Rebuild TempConvert4 Debug Start Without Debugging Web IE WSDL

  • 5 Web Web Web Web Web Web File Add New Project

  • Add New Project Project types Other Project Types Setup and Deployment Templates Web Setup Project TempConvert4WebSetup OK

  • File System Web Application Folder Solution Explorer TempConvert4WebSetup Add -> Project Output

  • Add Project Output Group Content Files OK

  • File System Web Application Folder bin bin Add -> Project Output

  • Add Project Output Group Primary Output Debug Symbols OK

  • bin Add -> Project Output Add Project Output Group TempConvert4Isapi Primary Output Debug Symbols OK

  • Solution Explorer TempConvert4WebSetup Build

  • TempConvert4\TempConvert4WebSetup\Debug TempConvert4WebSetup setup EXE Web setup Web

  • 13.3.3.4 Web Web Web Web Web Web TempConvert4Service Windows

  • 1 Web MFC Windows WebClient

  • IDCStaticIDC_STATICCStaticIDC_STATICCStaticIDC_STATICCEditIDC_FAHRENHEITm_FahrenheitdoubleCEditIDC_CELSIUSm_CelsiusdoubleCButtonIDC_BUTTON1CStaticIDC_STATICCStaticIDC_STATIC CStaticIDC_STATICCEditIDC_FAHRENHEIT1m_Fahrenheit1double CEditIDC_CELSIUS1m_Celsius1doubleCButtonIDC_BUTTON2CButtonIDC_BUTTON3

  • 2 Web Web Web SOAP SOAP Web Visual Studio .NET Web Web Web Web

  • Solution Explorer Class View Resource View Add Web Reference Project

  • Add Web Reference Add Web Reference Web

  • URL Web URL .disco Web URL .disco Web Start Browsing for Web Services Web web services on the local machine Web

  • Web URL .disco Go Web Start Browsing for Web Services Web

  • Web TempConvert4 Web

  • Add Reference Web CTempConvert4ServiceT CTempConvert4Service Solution Explorer Web 4

  • Web TempConvert4.h HelloWorld __CTempConvert4Service_HelloWorld_struct ConvertF2C __CTempConvert4Service_ ConvertF2C _struct ConvertC2F __CTempConvert4Service_ ConvertC2F _struct

  • HelloWorld SendRequest(_T("SOAPAction: \"#HelloWorld\"\r\n")); ConvertF2C SendRequest(_T("SOAPAction: \"# ConvertF2C \"\r\n")); ConvertC2F SendRequest(_T("SOAPAction: \"# ConvertC2F \"\r\n")); Web TempConvert4.disco result.discomap TempConvert4.wsdl Web

  • ConvertF2C

  • Web Web Web Web sproxy.exe Web Microsoft Native Web Service Proxy Generator.xtm

    sproxy /wsdl http://localhost/TempConvert4/TempConvert4.dll?Handler=GenTempConvert4WSDL /out:TempConvert4.h

  • 3 WebClientDlg.cpp #include TempConvert4.husing namespace TempConvert4Service; COM COM OnInitDialog COM BOOL CWebClientDlg::OnInitDialog() {CoInitialize(NULL);CDialog::OnInitDialog(); }

  • 4 Web 3 Web

  • void CWebClientDlg::OnBnClickedButton1(){// TODO: Add your control notification handler code hereUpdateData(TRUE);CTempConvert4Service Service;double bstrReturn;HRESULT hr = Service.ConvertF2C(m_Fahrenheit, &bstrReturn);if(SUCCEEDED(hr)){m_Celsius = bstrReturn;UpdateData(FALSE);}elseAfxMessageBox(_T("Web"));Service.Cleanup();}

  • void CWebClientDlg::OnBnClickedButton2(){// TODO: Add your control notification handler code hereUpdateData(TRUE);CTempConvert4Service Service;double bstrReturn;HRESULT hr = Service.ConvertC2F (m_Celsius1, &bstrReturn);if(SUCCEEDED(hr)){m_Fahrenheit1 = bstrReturn;UpdateData(FALSE);}elseAfxMessageBox(_T("Web"));Service.Cleanup();}

  • void CWebClientDlg::OnBnClickedButton3(){// TODO: Add your control notification handler code hereCoUninitialize();CDialog::OnCancel();}

    5 WebClient