DWORD EM_FileReceiving::ListeningThread(LPVOID lParam)
{
//SOCKET sListen;
CEIM02Dlg *pDlg = (CEIM02Dlg *)lParam;
// Create our listening socket
pEm_fileReceiving->m_sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == pEm_fileReceiving->m_sListen)
{
MessageBox(0,"socket() failed:%d\n",0,0);
return 1;
}
// Select the local interface and bind to it
SOCKADDR_IN local;
local.sin_addr.s_addr = htonl(INADDR_ANY);
local.sin_family = AF_INET;
local.sin_port = htons(5150);
int ret = ::bind(pEm_fileReceiving->m_sListen, (PSOCKADDR)&local, sizeof(SOCKADDR_IN));
if (SOCKET_ERROR == ret)
{
MessageBox(0,"bind() failed:%d\n",0,0);
return 1;
}
listen(pEm_fileReceiving->m_sListen, 5);
int iAddress = sizeof(SOCKADDR_IN);
SOCKET sClient;
SOCKADDR_IN addrClient;
EnterCriticalSection(&pEm_fileReceiving->cs);
while( m_bFileReceivingThread )
{
if (!m_bFileReceivingThread)
{
break;
}
sClient = accept(pEm_fileReceiving->m_sListen, (PSOCKADDR)&addrClient, &iAddress);
if (INVALID_SOCKET == sClient)
{
MessageBox(0,"accept() failed:%d\n", 0,0);
break;
}
char *szClientIP = new char [64];
strcpy(szClientIP, inet_ntoa(addrClient.sin_addr));
pDlg->PostMessage(WM_RECVFILE, (WPARAM)sClient, (LPARAM)szClientIP);
}
LeaveCriticalSection(&pEm_fileReceiving->cs);
return 1;
}
/////////////////////////////////////////////////////////////////////////////
// EM_FileReceiving message handlers
void EM_FileReceiving::Close()
{
m_bFileReceivingThread = FALSE;
closesocket(m_sListen);
BOOL bReuseaddr=TRUE;
setsockopt(m_sListen,SOL_SOCKET ,SO_REUSEADDR,(const char*)&bReuseaddr,sizeof(BOOL));
if (m_hThread != NULL)
{
TerminateThread(m_hThread, 0);
m_hThread = NULL;
}
}
求助,为什么已经终止了线程。线程里的函数还运行。
而且m_bFileReceivingThread 已将设置为false了
但回调函数中的循环,还在运行
加sleep(1000);也不可以
waiforsingobject等待也不可以。求高手。谢谢
很仔细地看了代码,但是没看出什么… while(false)只是跳出了当前循环,并不代表线程已经结束了。
我在Close函数中也用terminateThread终止了线程,我调试了,当close函数运行完,
直接走到listenThread函数中while循环中的accept函数,前面通过判断false退出循环,根本不运行,
而且我已经释放了端口,所以accept函数就错了。我就想解决,当close函数运行完毕,while循环直接结束
不走accept函数。有什么好方法解决吗??谢谢大神。
你需要的只是对accept函数做个异常处理