Mfc 简单的通讯模型(select模型)出错出错出错出错!!!大神大神大神快来!!!!
关键代码::BOOL CMfcSelectServerDlg::OnInitDialog()
{
...
...
...
int len=sizeof(SOCKADDR);
OnInitSocket();
HWND *lParameter=&m_hWnd;
HANDLE AcceptThread=CreateThread(NULL,0,AcceptProc,(LPVOID)lParameter,0,NULL);//此线程用来不断accept 客户
HANDLE WorkerThread=CreateThread(NULL,0,WorkerProc,(LPVOID)lParameter,0,NULL);//此线程用来处理收到的数据
CloseHandle(AcceptThread);
CloseHandle(WorkerThread);
return true;
}
DWORD WINAPI CMfcSelectServerDlg::AcceptProc(
LPVOID lpParameter)
{
SOCKADDR_IN ClientAddr;
int len=sizeof(SOCKADDR);
HWND* lphwnd=(HWND*)lpParameter;//取出对话框句柄 SOCKET ClientSock;
while(true)
{
char buf[50];
ClientSock=accept(m_ListenSock,(SOCKADDR*)&ClientAddr,&len);
sprintf(buf,"\n Accepted ClientUser:%s:%d",inet_ntoa(ClientAddr.sin_addr),ntohs(ClientAddr.sin_port));
ClientSockArr[num_conn]=ClientSock;
num_conn++;
::PostMessage(*lphwnd,UM_SOCK,0,(LPARAM)buf);
}
return 0;
}
DWORD WINAPI CMfcSelectServerDlg::WorkerProc(
LPVOID lpParameter)
{
HWND* lphwnd=(HWND*)lpParameter;//取出对话框句柄 int i;
fd_set fdread;
int ret;
struct timeval tv = {1, 0};
char buf[300];
while(true)
{
FD_ZERO(&fdread);
for(i=0;i<num_conn;i++)
FD_SET(ClientSockArr[i],&fdread);
ret=select(0,&fdread,NULL,NULL,&tv);
if(0==ret)
continue;
for(i=0;i<num_conn;i++)
if(FD_ISSET(ClientSockArr[i],&fread))
{
ret=recv(ClientSockArr[i],buf,300,0);
if(SOCKET_ERROR==ret)
{
char Temp[50];
sprintf(Temp,"Client socket %d closed.\n",ClientSockArr[i]);
::PostMessage(*lphwnd,UM_SOCK,0,(LPARAM)Temp);
closesocket(ClientSockArr[i]);
if(i<num_conn-1)
{
ClientSockArr[i]=ClientSockArr[num_conn-1];
i--;
num_conn--;
}
}
else
{
char strTemp[300];
sprintf(strTemp,"Client socket %d 说 %s.\n",ClientSockArr[i],buf);
::PostMessage(*lphwnd,UM_SOCK,0,(LPARAM)strTemp);
char *sendbuf="服务器已经收到!";
int len=sizeof("服务器已经收到!");
send(ClientSockArr[i],sendbuf,len+1,0);
}
}
}
return 0;
}
一定是这上面的三段代码中出了问题,服务器端一运行就通知出错。
注:我在对话框初始化函数中创建了两个线程,一个用来不断接收Accept客户端发来的连接
一个用来与客户端通讯。采用 select i/o模型。