主题:求套接字多线程编程中的服务器端发送数据函数
我有接收的代码
如下DWORD WINAPI recvFunProc( LPVOID lpParameter) /////接收线程
{
//char strIP;
char chat1[1024] = { 0 };
//int m=0;
fd_set fsRead;
timeval tm = { 0, 10000 };
char recvbuf[256] = {0};
char sendbuf[256] ="send from server";
while(1)
{
FD_ZERO( &fsRead );
for(int m=0;m<clientTopNum;m++) //将所有的client加入到select的检测中
FD_SET( client[m], &fsRead );
int iRet = select( clientTopNum+1, &fsRead, NULL, NULL, &tm );
if( SOCKET_ERROR == iRet ) //失败,即是无可读
{
cout << " Select failed, the client is to be shut down! " << endl;
return 1;
}
else
{
WaitForSingleObject( hMutex, INFINITE ); //占用互斥对象
for(int index=0;index<clientTopNum;index++)
{
if(FD_ISSET(client[index], &fsRead))
{
//cout<<"index:"<<index<<endl;
//empty(recvbuf);
memset(recvbuf, 0, sizeof(recvbuf));
recv(client[index], recvbuf, sizeof(recvbuf), 0);
//if(recvbuf[0]==0x20) //如果接收到的是空格的话表示有一个客户端退出 0x20表示空格
if(strlen(recvbuf)==0)
{
// cout<<"一个客户端自行退出,socket值为:"<<client[index]<<endl;
client[index]=client[clientTopNum-1]; //将最后一个放到刚刚退出的client那里去
client[clientTopNum-1]=0; //保证所有未退出的客户端都在前面
if(clientTopNum==0)
return 0;
clientTopNum--;
}
else
{
cout<<recvbuf<<endl;
send(client[index],sendbuf,sizeof(recvbuf),0);
cout<<sendbuf<<endl;
/* for(int n=0;n<clientTopNum;n++)
{
if(n!=index)
send(client[n],sendbuf,sizeof(recvbuf),0);
}
*/
// cout<<"**************结束**************"<<endl;
}
}
}
ReleaseMutex( hMutex );
}
}
}
可是,我将它改为发送端时却不行。
如下DWORD WINAPI recvFunProc( LPVOID lpParameter) /////接收线程
{
//char strIP;
char chat1[1024] = { 0 };
//int m=0;
fd_set fsRead;
timeval tm = { 0, 10000 };
char recvbuf[256] = {0};
char sendbuf[256] ="send from server";
while(1)
{
FD_ZERO( &fsRead );
for(int m=0;m<clientTopNum;m++) //将所有的client加入到select的检测中
FD_SET( client[m], &fsRead );
int iRet = select( clientTopNum+1, &fsRead, NULL, NULL, &tm );
if( SOCKET_ERROR == iRet ) //失败,即是无可读
{
cout << " Select failed, the client is to be shut down! " << endl;
return 1;
}
else
{
WaitForSingleObject( hMutex, INFINITE ); //占用互斥对象
for(int index=0;index<clientTopNum;index++)
{
if(FD_ISSET(client[index], &fsRead))
{
//cout<<"index:"<<index<<endl;
//empty(recvbuf);
memset(recvbuf, 0, sizeof(recvbuf));
recv(client[index], recvbuf, sizeof(recvbuf), 0);
//if(recvbuf[0]==0x20) //如果接收到的是空格的话表示有一个客户端退出 0x20表示空格
if(strlen(recvbuf)==0)
{
// cout<<"一个客户端自行退出,socket值为:"<<client[index]<<endl;
client[index]=client[clientTopNum-1]; //将最后一个放到刚刚退出的client那里去
client[clientTopNum-1]=0; //保证所有未退出的客户端都在前面
if(clientTopNum==0)
return 0;
clientTopNum--;
}
else
{
cout<<recvbuf<<endl;
send(client[index],sendbuf,sizeof(recvbuf),0);
cout<<sendbuf<<endl;
/* for(int n=0;n<clientTopNum;n++)
{
if(n!=index)
send(client[n],sendbuf,sizeof(recvbuf),0);
}
*/
// cout<<"**************结束**************"<<endl;
}
}
}
ReleaseMutex( hMutex );
}
}
}
可是,我将它改为发送端时却不行。