你先简单看一下这个代码:class CSockThread : public CWinThread { // ... Other function and member declarations protected: CSocket m_sConnected; };SOCKET hConnected;BOOL CSockThread::InitInstance() { // Attach the socket object to the socket handle // in the context of this thread. m_sConnected.Attach(hConnected); return TRUE; }// This listening socket has been constructed // in the primary thread. void CListeningSocket::OnAccept(int nErrorCode) { // This CSocket object is used just temporarily // to accept the incoming connection. CSocket sConnected; Accept(sConnected); // Detach the newly accepted socket and save // the SOCKET handle. hConnected = sConnected.Detach(); // After detaching it, it should no longer be // used in the context of this thread. // Start the other thread. AfxBeginThread(RUNTIME_CLASS(CSockThread)); }
因为CSocket是与CWnd有很多关联的(因为要使用AsyncSelect(),使网络消息映射为窗口消息,以便程序处理),而CWnd是跟线程的(关系到线程的消息队列和资源管理等问题)。所以不能这样使用CSocket对象。
如果真的要在多线程环境下使用socket,还是使用socket()和WSASocket()生成socket,直接用API做吧,那就完全没有问题了。关于某些MFC类,如CWnd在多线程环境下的使用问题,MSDN有提及,还是看看去吧。
或者直接使用WSA开头的Winsock2 API,他们是异步的。
是这里出错VERIFY(AsyncSelect(0));To: neccui
是new出来的,在进入线程前没有任何操作!不应该被释放了!jerrytse说的似乎很有道理啊!to:jerrytse
我还想用CSocket的事件呢,用API怎么实现异步功能?请说详细点!多谢!to:tcl_tk
那用CAsyncSocket而不是CScoket我试了也不成啊!请问以WSA开头的Winsock2 API怎么用?请详细说明!以上各位都会完事后都会加分,当然不都会是70分,大家再帮我想想!
再次感谢各位的帮助!
{
// ... Other function and member declarations
protected:
CSocket m_sConnected;
};SOCKET hConnected;BOOL CSockThread::InitInstance()
{
// Attach the socket object to the socket handle
// in the context of this thread.
m_sConnected.Attach(hConnected); return TRUE;
}// This listening socket has been constructed
// in the primary thread.
void CListeningSocket::OnAccept(int nErrorCode)
{
// This CSocket object is used just temporarily
// to accept the incoming connection.
CSocket sConnected;
Accept(sConnected); // Detach the newly accepted socket and save
// the SOCKET handle.
hConnected = sConnected.Detach(); // After detaching it, it should no longer be
// used in the context of this thread. // Start the other thread.
AfxBeginThread(RUNTIME_CLASS(CSockThread));
}
BOOL CAsyncSocket::AsyncSelect(long lEvent)
{
ASSERT(m_hSocket != INVALID_SOCKET); _AFX_SOCK_THREAD_STATE* pState = _afxSockThreadState;
ASSERT(pState->m_hSocketWindow != NULL); return WSAAsyncSelect(m_hSocket, pState->m_hSocketWindow,
WM_SOCKET_NOTIFY, lEvent) != SOCKET_ERROR;
}
看是线程的时候,在主线程里面,把CSocket.Detach出来,把SOCKET句柄传给你的线程在线程开始的时候,把socket句柄attach上去UINT DoWithHearSocket(LPVOID nt)
{
SOCKET hSocket = (SOCKET)nt;
CHearSocket m_socket;
m_socket.Attach( hSocket );
m_socket.Close();
...