下面的语句在Mainframe的事件中运行正常,
但是如果用AfxBeginThread来新开一个线程,就会出错,请问这是什么原因??     CString str="10.214.40.101";
    CSocket* listener=new CSocket();
    if(!listener->Create(1860,SOCK_STREAM,str))
        return;
    listener->Listen(5);
报错的位置在
CAsyncSocket::AttachHandle()中。
请问这个问题是不是和MFC的SDI有关啊??
因为在Dialog中这样开线程是没有问题的。

解决方案 »

  1.   

    这是一个服务器端的侦听程序,其中listener->Create的第三个参数在服务器端是不能指定的,应该是NULL。
      

  2.   

    参考PRB: Assertion Failed on Line 837 - Sockcore.cpp Q140527
    CAUSE
    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. RESOLUTION
    As already mentioned, a CAsyncSocket object should be used only in the context of a single thread. If you need to switch the thread that is accessing a SOCKET connection with another thread, then you should use a separate CAsyncSocket object in each thread, and use the Detach and Attach functions to attach the CAsyncSocket object to the SOCKET handle in the thread that is about to use the socket. Use this sequence:Use Detach() to detach the CAsyncSocket object from the SOCKET handle in the thread that is currently using the CAsyncSocket object.
    Use Attach() to attach a different CAsyncSocket object to the SOCKET handle while in the context of the MFC UI thread in which you wish to begin accessing the SOCKET connection.
    The code shown in the "Code Sample" section of this article shows how to handle the moment when a listening socket accepts a connection request and then begins a new thread to handle the new connection.
    ...
      

  3.   

    gracezhu(kingzai) : got it. 3x!!
    看来都要改API了,ft...
      

  4.   

    Up。PRB是什么??在哪里可以找到?
      

  5.   

    我也看得很郁闷,服务端程序你指定IP做啥?还固定只准IP的机器连接?
      

  6.   

    单看你上面那几行代码,没什么大问题。如果出线多线程环境下,可能是同步的问题。服务器不用指定IP,但你如果有多张网卡或配置了多个IP,可以将服务绑定到指定的适配置,或指定的IP上。要达到实用的话,你需要作用GetAdapterInfo枚举系统中的所有配置器和IP地址。