这几天都在做密码课程实践,其中需要做一个双机密码演示,需要用DH密钥交换协议交换密钥,然后再用一种对称密钥对双机通讯信息进行加解密。我用MFC来做的,主程序采用CAsyncSocket异步通讯的方式。选择CAsyncSocket是因为它是异步的,可以采用实践触发模式。在进行文件传输的时候,我采用了多线程加CSocket的方法,即在一个新创建的线程内采用CSocket同步模式传输文件。整个工程采用Static库。在Debug下,文件传输一切正常,可是到了Release底下一旦在新创建新线程CSocket调用Create之后,就抛出异常了,程序异常退出。上网查了半天,终于在优快云的一个2002年的帖子上发现原因。原帖如下:
FIX: Unhandled Exception Using MFC Sockets in Visual C++ 6.0
The information in this article applies to:
The Microsoft Foundation Classes (MFC), when used with:
Microsoft Visual C++, 32-bit Enterprise Edition 6.0
Microsoft Visual C++, 32-bit Professional Edition 6.0
Microsoft Visual C++, 32-bit Learning Edition 6.0
Symptoms
When using MFC sockets in secondary threads in a statically linked MFC Visual C++ 6.0 application, an unhandled exception occurs.
Cause
The reason for the unhandled exception is that an object of type CMapPtrToPtr pointer, pointed to by m_pmapSocketHandle, is never created.
Resolution
The handle maps used by the sockets need to be created for each thread. The following code shows a function to do this:
void SocketThreadInit()
{
#ifndef _AFXDLL
#define _AFX_SOCK_THREAD_STATE AFX_MODULE_THREAD_STATE
#define _afxSockThreadState AfxGetModuleThreadState()
_AFX_SOCK_THREAD_STATE* pState = _afxSockThreadState;
if(pState->m_pmapSocketHandle == NULL)
pState->m_pmapSocketHandle = new CMapPtrToPtr;
if(pState->m_pmapDeadSockets == NULL)
pState->m_pmapDeadSockets = new CMapPtrToPtr;
if(pState->m_plistSocketNotifications == NULL)
pState->m_plistSocketNotifications = new CPtrList;
#endif
}
This function should be called once in each secondary thread before the first socket is created in the new thread.
在每个线程开始出调用SocketThreadInit函数,就没有问题了。
文章出处:DIY部落(http://www.diybl.com/course/3_program/c++/cppjs/20090302/156505.html)

本文介绍使用MFC实现双机密码演示过程中遇到的问题及解决方法。通过在新线程中初始化套接字资源,避免了静态链接MFC环境下发生的异常。
4550

被折叠的 条评论
为什么被折叠?



