Windows CSocket 多线程编程用Share Liabrary没错,但只要是用了Static Library就出错

用Share Liabrary没错,但只要是用了Static Library就会出错,是一样的错误。

1.m_Socket.Create();

2.CAsyncSocket::Create(nSocketPort, nSocketType, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, lpszSocketAddress);

3.if (Socket(nSocketType, lEvent)) { ... }

 4.CAsyncSocket::AttachHandle(m_hSocket, this, FALSE);

 5.ASSERT(CAsyncSocket::LookupHandle(hSocket, bDead) == NULL);

 6.pSocket = (CAsyncSocket*) pState-> m_pmapSocketHandle-> GetValueAt((void*)hSocket);

7.if (m_pHashTable == NULL) return NULL;

第7句出错。

 

 http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q193101&

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,为每个线程都分配一个全局数组之类的来管理CSocket对象与socket句柄

 

解决办法:

一,在每个socket Create之前调用SocketThreadInit

二,主线程必须调用AfxSocketInit

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值