今天又在socket多线程中调试了半天,在线程中传了参数psocket,一开始定义的 MySocket pconSocket,启动线程为 hd = CreateThread(NULL, 0, conThread, &pconSocket, 0 ,NULL);客户端信息总是无法接收到,看了半天才恍然大悟,psocket对象的生命周期只在当前函数中,进入线程后已销毁,所有无法接收,已经第二次犯这种错误了,诶....。把psocke改为指针即可,如下:
while (!m_pdlg->m_stopServer)
{
MySocket *pconSocket = new MySocket();
pconSocket->setSocket(accept(lisScoket, (sockaddr *)&addr_client, &nAddrLen));
if (INVALID_SOCKET == *pconSocket->getSocket())
{
AfxMessageBox("failure accept");
continue;
}
m_pdlg->m_listMsg.AddString("new client connect");
HANDLE hd;
hd = CreateThread(NULL, 0, conThread, pconSocket, 0 ,NULL);
CloseHandle(hd);
pconSocket = NULL;
}
}
DWORD WINAPI ServerConmunicate::conThread(LPVOID lpParameter)
{
MySocket * pSocket = (MySocket *)lpParameter;
char buffer[1024]={0};
while(true)
{
if (m_pdlg->m_stopServer)//服务器停止服务
{
pSocket->serverStop();
break;
}
recv(*(pSocket->getSocket()), buffer, sizeof(buffer), 0); //接收数据
pSocket->distinguishType(buffer);//根据接收的数据分别处理
if (pSocket->m_isExist)//用户已退出
{
break;
}
}
if (pSocket != NULL)
{
delete pSocket;
pSocket = NULL;
}
AfxMessageBox("connect thread exit");
return 0;
}