我在线程中调用recvfrom函数,监听来自客户端的消息.但是现在发现无法监听多个客户端.
只能接收到最先发来消息的客户端.
分不多了,还请见谅.谢谢!
我的代码如下:
CWorkThread *thread_net;
CSrvSocket *sock;
void NetThreadProc(void *p); //网络监听线程
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
....
//启动网络通讯线程
thread_net->DoWork((LPTHREAD_START_ROUTINE)::NetThreadProc, NET);
if (thread_net->m_bNetIsSuspend == true)
{
printf("-------------->启动网络通讯线程<--------------\n");
thread_net->ResumeThread(NET);
}
while(true)
{
Sleep(1000);
}
....
//关闭监听套接字
closesocket(sock->socket)
}
void NetThreadProc(void *p)
{
....
while (1)
{
int ret;
int clientlen;
clientlen = sizeof(sock->RecvClient);
if (sock->m_isockState != BINDED)
{
return;
}
ret = ::recvfrom(sock->socket, RecvMsg, sizeof(RecvMsg), 0, (SOCKADDR *)&sock->RecvClient, &clientlen);
if (ret == SOCKET_ERROR)
{
return;
}
ret = ::connect(sock->socket, (SOCKADDR *)&this->RecvClient, clientlen);
ret = ::sendto(sock->socket, buffer.GetBuffer(), buffer.GetLength(), 0, (SOCKADDR *)&sock->RecvClient, clientlen);
....
}
}
另外:
int CWorkThread::DoWork(LPTHREAD_START_ROUTINE Process, int flag)
{
if (flag == NET) //NET线程 (Process = NetThreadProc)
{
//创建NET线程,并保存线程句柄m_hNetThread
this->m_hNetThread = ::CreateThread( NULL, 0, Process, NULL, CREATE_SUSPENDED, &this->m_dwNetThreadId);
//设置DB线程挂起标志
this->m_bNetIsSuspend = true;
}
}
4 个解决方案
#1
有人么? 虽然今天周末,但是还是拜托各位高人帮一下啊 T_T 折腾了好久了....
#2
ret = ::recvfrom(sock->socket, RecvMsg, sizeof(RecvMsg), 0, (SOCKADDR *)&sock->RecvClient, &clientlen);
////////////////////////
每次你只对sock->socket进行接收,当然只能收到一个了
////////////////////////
每次你只对sock->socket进行接收,当然只能收到一个了
#3
能否每次调用线程前先创建socket,然后在线程里接收,在线程尾closesocket() ?? 是这个意思么?
#4
UP!
#1
有人么? 虽然今天周末,但是还是拜托各位高人帮一下啊 T_T 折腾了好久了....
#2
ret = ::recvfrom(sock->socket, RecvMsg, sizeof(RecvMsg), 0, (SOCKADDR *)&sock->RecvClient, &clientlen);
////////////////////////
每次你只对sock->socket进行接收,当然只能收到一个了
////////////////////////
每次你只对sock->socket进行接收,当然只能收到一个了
#3
能否每次调用线程前先创建socket,然后在线程里接收,在线程尾closesocket() ?? 是这个意思么?
#4
UP!