在ATL中支持MFC的CSocket

类别:VC语言 点击:0 评论:0 推荐:

SendFile 

 

1.         功能:

 

SendFile 可传送(任意形式)单个文件(档),如果为WEB页,则同时可以将其同名  . files目录下的所有文件一起传送。

 

2、设计思路:

 

¨         根据用户选择需要传送的文件,获得文件的一些相关信息(主要是文件名),然后开始传送文件到服务器或者是客户端;

¨         判断是否存在同名 . files 目录,如果存在的话,则遍历该目录,每获得一个文件名,即将该文件发送;

¨         遍历结束,释放所有资源。

 

3、控件使用:

 

             控件有含有唯一一个Daul接口 FileWork 运行时不可见;该接口含有唯一一个方法 TransDoc

              TransDoc 参数说明:

¨         BSTR ServerName :为DOMINO服务器名;

¨         BSTR HostName    : 为主机名或者主机IP地址;

¨         UINT Port        :主机端口号;

¨         BSTR User            :当前用户名;

¨         BSTR Password     :当前用户密码;

¨         BSTR DocFilename :文件全名;

¨         BSTR uDatabase    :Domino 数据库名;

¨         BSTR uForm         :Domino 表单名;

        注:BSTR 为Basic String/Binary String,在VB中表现为String 类型。

 

4、范例:

 

 

              下面我给出一个在VB中使用该空间的范例:

¨         新建一个标准EXE工程;

¨         在Form上添加一个TEXTBOX,两个COMMAND BUTTON,一个COMMON DIALOG。属性如下:

      Control             name                   Property

                              TextBox               txtFilename     

                      Command Button1                                        caption 浏览…

Command Button2                        caption 发送文件

  

 

代码:

 

Private Sub Command1_Click()

   

    CommonDialog1.ShowOpen

   

    txtFilename.Text = CommonDialog1.FileName

End Sub

 

Private Sub Command2_Click()

FileWork1.TransDoc  "Domserver", "10.128.0.3", 1028, "zhangchunye",    "zhangchunye", txtFilename.Text, "Test", "Test"

End Sub

现代码:

 

// FileWork.cpp : Implementation of CFileWork

 

#include "stdafx.h"

#include "SendFile.h"

#include "FileWork.h"

 

 

#include <string.h>

/////////////////////////////////////////////////////////////////////////////

// CFileWork

 

 

 

 

STDMETHODIMP CFileWork::TransDoc(BSTR ServerName,BSTR Hostname,int Port,BSTR User,BSTR password,BSTR DocFilename,BSTR uDatabase,BSTR  uForm)

{

       AFX_MANAGE_STATE(AfxGetStaticModuleState())

 

       // TODO: Add your implementation code here

      

       USES_CONVERSION;

      

      

       AfxSocketInit(NULL);

       CSocket sockClient;

       sockClient.Create();

 

       m_HostName = OLE2T(Hostname);

       m_Port       = Port;     

//     MessageBox(m_HostName,_T("HostName!"),MB_OK);

      

       if(!sockClient.Connect(m_HostName,Port))

       {

              AfxMessageBox("连接到对方机器失败!");

              return 0;

       }

 

       m_UserName = OLE2T(User) ;                   

       m_Password = OLE2T(password) ;

       //发送用户名和密码要求登陆

 

       //用户名和密码需要加密。然后再发送。

       sockClient.Send(m_UserName,strlen(m_UserName));

       sockClient.Send(m_Password,strlen(m_Password));

      sockClient.Send(m_ServerName,strlen(m_ServerName));

       sockClient.Send(m_Database,strlen(m_Database));

       sockClient.Send(m_Form,strlen(m_Form));

       ////用户名和密码通过验证,可以发送文件

 

       char* filename = OLE2T(DocFilename);

       CFile myFile;

       if(!myFile.Open( filename ,/* conversion BSTR to char* */

                                   CFile::modeRead | CFile::typeBinary))

       {

             

              return 0;

       }

       SOCKET_STREAM_FILE_INFO        StreamFileInfo;

       WIN32_FIND_DATA             FindFileData;

 

       FindClose(FindFirstFile(myFile.GetFilePath(),&FindFileData));

    memset(&StreamFileInfo,0,sizeof(SOCKET_STREAM_FILE_INFO));

    strcpy(StreamFileInfo.szFileTitle,myFile.GetFileName());

 

    StreamFileInfo.nFileSizeLow         =       FindFileData.nFileSizeLow;

 

       sockClient.Send(&StreamFileInfo,sizeof(SOCKET_STREAM_FILE_INFO));

 

       UINT dwRead=0;

       while(dwRead<StreamFileInfo.nFileSizeLow)

       {

              byte* data = new byte[5120];

              UINT dw=myFile.Read(data, 5120);

              sockClient.Send(data, dw);

              dwRead+=dw;

       }

       //以下代码设置.htm同名  .files目录。

       char szCurDir[256] ;

  

    ::GetCurrentDirectory(sizeof(szCurDir),szCurDir);

      LPCSTR filetitle;

       filetitle = (LPCTSTR) myFile.GetFileTitle();

       strcat(szCurDir,"\\");

       strcat(szCurDir,filetitle);

       strcat(szCurDir,".files\\");

 

       //设置目录结束。

 

      

       myFile.Close();

       Recurse(T2OLE(szCurDir));

 

       LPTSTR m_EndCode = "000";

       sockClient.Send(m_EndCode,strlen(m_EndCode));

       MessageBox(_T("信息发布成功!"),_T("信息发布"),MB_ICONINFORMATION|MB_OK);

       sockClient.Close();

       return S_OK;

};

 

// stdafx.h : include file for standard system include files,

//      or project specific include files that are used frequently,

//      but are changed infrequently

 

#if !defined(AFX_STDAFX_H__0AC71DA2_A0CD_4AA6_8E23_5C459FD52A59__INCLUDED_)

#define AFX_STDAFX_H__0AC71DA2_A0CD_4AA6_8E23_5C459FD52A59__INCLUDED_

 

#if _MSC_VER > 1000

#pragma once

#endif // _MSC_VER > 1000

 

#define STRICT

#ifndef _WIN32_WINNT

#define _WIN32_WINNT 0x0400

#endif

#define _ATL_APARTMENT_THREADED

 

#include <afxwin.h>

#include <afxdisp.h>

 

#include <atlbase.h>

//You may derive a class from CComModule and use it if you want to override

//something, but do not change the name of _Module

extern CComModule _Module;

#include <atlcom.h>

#include <atlhost.h>

#include <mshtml.h>

#include <exdisp.h>

#include <atlctl.h>

#include <afxsock.h>   

 

#include <ole2.h>

 

 

//{{AFX_INSERT_LOCATION}}

// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

 

#endif // !defined(AFX_STDAFX_H__0AC71DA2_A0CD_4AA6_8E23_5C459FD52A59__INCLUDED)

 

 

 

// This file will be processed by the MIDL tool to

// produce the type library (SendFile.tlb) and marshalling code.

 

import "oaidl.idl";

import "ocidl.idl";

#include "olectl.h"

      

 

       [

              object,

              uuid(68C3C9C3-08CF-4B80-8C8A-1A1503EAF27B),

              dual,

              helpstring("IFileWork Interface"),

              pointer_default(unique)

       ]

       interface IFileWork : IDispatch

       {

 

              [id(1), helpstring("method TransDoc")] HRESULT TransDoc([in]BSTR ServerName,[in]BSTR Hostname,[in]int Port,[in]BSTR User,[in]BSTR password,[in]BSTR DocFilename,[in]BSTR uDatabase,[in]BSTR  uForm);

 

       };

 

[

       uuid(AACF2ED6-2C63-4A9F-B2DB-05FD8EBDDB7E),

       version(1.0),

       helpstring("SendFile 1.0 Type Library")

]

library SENDFILELib

{

       importlib("stdole32.tlb");

       importlib("stdole2.tlb");

 

       [

              uuid(E3A8C76D-FD5C-4DF6-9D90-DDD47EC8567C),

              helpstring("_IFileWorkEvents Interface")

       ]

       dispinterface _IFileWorkEvents

       {

              properties:

              methods:

       };

 

       [

              uuid(4D8F2BCB-0546-4DFA-AC6E-C2C3BC26BE38),

              helpstring("FileWork Class")

       ]

       coclass FileWork

       {

              [default] interface IFileWork;

              [default, source] dispinterface _IFileWorkEvents;

       };

};

 

 

 

 

      

// FileWork.h : Declaration of the CFileWork

 

#ifndef __FILEWORK_H_

#define __FILEWORK_H_

 

#include "resource.h"       // main symbols

#include <atlctl.h>

#include "SendFileCP.h"

 

/////////////////add class

typedef struct _SOCKET_STREAM_FILE_INFO {

 

    TCHAR       szFileTitle[128];                   //文件的标题名

    DWORD       dwReserved1;                        //保留,为0

 

} SOCKET_STREAM_FILE_INFO, * PSOCKET_STREAM_FILE_INFO;

/////////////////////////////////////////////////////////////////////////////

// CFileWork

class ATL_NO_VTABLE CFileWork :

       public CComObjectRootEx<CComSingleThreadModel>,

       public IDispatchImpl<IFileWork, &IID_IFileWork, &LIBID_SENDFILELib>,

       public CComControl<CFileWork>,

       public IPersistStreamInitImpl<CFileWork>,

       public IOleControlImpl<CFileWork>,

       public IOleObjectImpl<CFileWork>,

       public IOleInPlaceActiveObjectImpl<CFileWork>,

       public IViewObjectExImpl<CFileWork>,

       public IOleInPlaceObjectWindowlessImpl<CFileWork>,

       public ISupportErrorInfo,

       public IConnectionPointContainerImpl<CFileWork>,

       public CComCoClass<CFileWork, &CLSID_FileWork>,

       public CProxy_IFileWorkEvents< CFileWork >

{

public:

       CFileWork()

       {

              m_pUnkMarshaler = NULL;

       }

 

DECLARE_GET_CONTROLLING_UNKNOWN()

DECLARE_REGISTRY_RESOURCEID(IDR_FILEWORK)

 

DECLARE_PROTECT_FINAL_CONSTRUCT()

 

BEGIN_COM_MAP(CFileWork)

       COM_INTERFACE_ENTRY(IFileWork)

       COM_INTERFACE_ENTRY(IDispatch)

       COM_INTERFACE_ENTRY(IViewObjectEx)

       COM_INTERFACE_ENTRY(IViewObject2)

       COM_INTERFACE_ENTRY(IViewObject)

       COM_INTERFACE_ENTRY(IOleInPlaceObjectWindowless)

       COM_INTERFACE_ENTRY(IOleInPlaceObject)

       COM_INTERFACE_ENTRY2(IOleWindow, IOleInPlaceObjectWindowless)

       COM_INTERFACE_ENTRY(IOleInPlaceActiveObject)

       COM_INTERFACE_ENTRY(IOleControl)

       COM_INTERFACE_ENTRY(IOleObject)

       COM_INTERFACE_ENTRY(IPersistStreamInit)

       COM_INTERFACE_ENTRY2(IPersist, IPersistStreamInit)

       COM_INTERFACE_ENTRY(ISupportErrorInfo)

       COM_INTERFACE_ENTRY(IConnectionPointContainer)

       COM_INTERFACE_ENTRY_AGGREGATE(IID_IMarshal, m_pUnkMarshaler.p)

       COM_INTERFACE_ENTRY_IMPL(IConnectionPointContainer)

END_COM_MAP()

 

BEGIN_PROP_MAP(CFileWork)

       PROP_DATA_ENTRY("_cx", m_sizeExtent.cx, VT_UI4)

       PROP_DATA_ENTRY("_cy", m_sizeExtent.cy, VT_UI4)

       // Example entries

       // PROP_ENTRY("Property Description", dispid, clsid)

       // PROP_PAGE(CLSID_StockColorPage)

END_PROP_MAP()

 

BEGIN_CONNECTION_POINT_MAP(CFileWork)

CONNECTION_POINT_ENTRY(DIID__IFileWorkEvents)

END_CONNECTION_POINT_MAP()

 

BEGIN_MSG_MAP(CFileWork)

       CHAIN_MSG_MAP(CComControl<CFileWork>)

       DEFAULT_REFLECTION_HANDLER()

END_MSG_MAP()

// Handler prototypes:

//  LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);

//  LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);

//  LRESULT NotifyHandler(int idCtrl, LPNMHDR pnmh, BOOL& bHandled);

 

 

 

       HRESULT FinalConstruct()

       {

              return CoCreateFreeThreadedMarshaler(

                     GetControllingUnknown(), &m_pUnkMarshaler.p);

       }

 

       void FinalRelease()

       {

              m_pUnkMarshaler.Release();

       }

 

       CComPtr<IUnknown> m_pUnkMarshaler;

 

// ISupportsErrorInfo

       STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid)

       {

              static const IID* arr[] =

              {

                     &IID_IFileWork,

              };

              for (int i=0; i<sizeof(arr)/sizeof(arr[0]); i++)

              {

                     if (InlineIsEqualGUID(*arr[i], riid))

                            return S_OK;

              }

              return S_FALSE;

       }

 

// IViewObjectEx

       DECLARE_VIEW_STATUS(VIEWSTATUS_SOLIDBKGND | VIEWSTATUS_OPAQUE)

 

// IFileWork

public:

       LPTSTR m_Form;

       LPTSTR m_Database;

       HRESULT SendFile(BSTR DocFile);

       void Recurse(BSTR FilePath);

             

       LPTSTR m_ServerName;

 

       LPTSTR m_HostName;

       int m_Port;

       LPTSTR m_UserName;

       LPTSTR m_Password;

       CSocket sockClient;

 

STDMETHOD(TransDoc)(/*[in]*/BSTR  ServerName,/*[in]*/BSTR Hostname,/*[in]*/int Port,/*[in]*/BSTR User,/*[in]*/BSTR password,/*[in]*/BSTR DocFilename,/*[in]*/BSTR uDatabase,/*[in]*/BSTR  uForm);

 

       HRESULT OnDraw(ATL_DRAWINFO& di)

       {

              RECT& rc = *(RECT*)di.prcBounds;

              Rectangle(di.hdcDraw, rc.left, rc.top, rc.right, rc.bottom);

 

              SetTextAlign(di.hdcDraw, TA_CENTER|TA_BASELINE);

              LPCTSTR pszText = _T("ATL 3.0 : FileWork");

              TextOut(di.hdcDraw,

                     (rc.left + rc.right) / 2,

                     (rc.top + rc.bottom) / 2,

                     pszText,

                     lstrlen(pszText));

 

              return S_OK;

       }

};

 

#endif //__FILEWORK_H_

 

 

本文地址:http://com.8s8s.com/it/it2780.htm