我是靠谱客的博主 糊涂红酒,最近开发中收集的这篇文章主要介绍关于mfc下多线程socket出错,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

问?:

我用CSocket写通信程序,但执行到下面的函数时总出错,是什么原因?
是多线程通信,每个线程创建了一个套接字:CMySocket *m_pClientSocket = New CMySocket;
然后在OnSendSocket函数中调用:m_pClientSocket->Send(str,len);
如果消息很少,或者中间有Sleep,则没有错误,否则必然出现ASSERT(pState->m_hSocketWindow != NULL);的错误。
听说
1 是一个Bug,我用VC 5.0也打了sp5,
2 同一个套接字不能在不同的线程传输,但是我每一个线程创建了一个单独的套接字
3 没有调用AfxSockInit(),但是我在每个线程的初始化中都调用了这个函数。
现在实在没有办法解决,请大家帮忙,感谢!


下面的函数是 .../MFC/SRC/SOCKCORE.CPP 里的函数。
BOOL CSocket::PumpMessages(UINT uStopFlag)
{
// The same socket better not be blocking in more than one place.
ASSERT(m_pbBlocking == NULL);

_AFX_SOCK_THREAD_STATE* pState = _afxSockThreadState;

ASSERT(pState->m_hSocketWindow != NULL); //这句出错这句出错这句出错这句出错

BOOL bBlocking = TRUE;
m_pbBlocking = &bBlocking;

 

 

答:(from microsoft)

Most frequently, this problem is due to the sharing of CSocket objects between multiple threads.

A CSocket object should be used only in the context of a single thread because the SOCKET handle encapsulated by a CAsyncSocket object is stored in a per-thread handle map. (CSocket is derived from CAsyncSocket.) Other information is stored on a per-thread basis, including a hidden notification window that MFC uses for socket notifications.

The assertion failure line, which can be found in Sockcore.cpp in the /Msvc20/Mfc/Src directory, is:

   ASSERT(pThreadState->m_hSocketWindow != NULL);

This assertion failure occurs because the CSocket object was either created or accepted in the context of another thread. The socket notification window was created in a different thread, and the m_hSocketWindow for the current thread is NULL, thus the assertion failure.

 

 

最后

以上就是糊涂红酒为你收集整理的关于mfc下多线程socket出错的全部内容,希望文章能够帮你解决关于mfc下多线程socket出错所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(35)

评论列表共有 0 条评论

立即
投稿
返回
顶部