要在程序启动时用Socket访问远程服务器进行登陆检查,但是又要防止超时,为此,不得已采用了多线程(由于我在InitInstance中加入了相关代码,此时消息处理好像还不能起效<猜测而已,没有研究过MFC的实现机制,^_^>),但是,仍然等待超时,不知何故,请各路大侠帮忙症断一下。
我的实现代码如下:
//初始化线程参数,略
...
//启动线程进行数据发送
AfxBeginThread(SendDataProc, &dts);
if (WAIT_OBJECT_0 == WaitForSingleObject(m_eventComm, nTimeOut))
{
if (dts.commStatus == COMM_SUCCEED)
{
return true; //通过检查
}
else
{
AfxMessageBox("用户名或密码不正确!");
continue;
}
}
else
{
dts.bTerminate = true;
AfxMessageBox("服务器处理超时!");
continue;
}以下是工作线程函数代码:
UINT SendDataProc(LPVOID pParam)
{
CString strIP, strPort, strTimeOut;
ASSERT(theApp.GetConfig("SOPIP", strIP));
ASSERT(theApp.GetConfig("SOPPORT", strPort));
ASSERT(theApp.GetConfig("TIMEOUT", strTimeOut)); DTS_STRUCT* pdts = (DTS_STRUCT*)pParam; CCommSocket commSocket;
if (!commSocket.Create ())
{
AfxMessageBox("创建套接字失败!");
return false;
}
if (!commSocket.Connect(strIP, atoi(strPort)))
{
AfxMessageBox("连接服务器失败!");
return false;
}
commSocket.SendDataToServer(pdts->pszData, pdts->pCommHeader, pdts->ppszDataRet, &pdts->bTerminate, StopCommFunc); MSG msg;
while (!pdts->bTerminate) //捕获并处理消息,以正确处理收到服务器数据返回消息,但仍然无法正确接收,为什么呢?
{
::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
::TranslateMessage(&msg);
Sleep(1);
}
pdts->commStatus = commSocket.GetCommState();
pdts->pEvent->SetEvent();

return 0L;
}