用VC编写C/S消息传送程序
2008-11-14 19:37:11 来源:WEB开发网4.在析构函数中完成必需的清除操作:
CServerView::~CServerView()
{
if(m_bInitialized)
WSACleanup();
closesocket(m_sock);
if(m_hListenThread)
::TerminateThread(m_hListenThread,0);
}
5.定义接收和处理消息的线程:
long WINAPI Listen(CServerView *pView)
{
char msg[2000]="";
intnchar;
SOCKADDR_IN saClnt;
int saClntLen;
while(1)
{
saClntLen=sizeof(saClnt);
nchar=recvfrom(pView->m_sock,msg,1024,0,(PSOCKADDR)&saClnt,&saClntLen);
if(nchar<0) { pView->m_data[pView->count++]+="Error in recvfromn";
pView->InvalidateRect(NULL);
}
else
{
switch(msg[0])
{
case'A':
wsprintf(msg,"A: Client from %s
attachedn",inet_ntoa(saClnt.sin_addr));
pView->m_data[pView->count++]=msg;
pView->flag=TRUE;
pView->InvalidateRect(NULL);
pView->Isconnect=TRUE;
pView->saClnt=saClnt;
pView->saClntLen=saClntLen;
sendto(pView->m_sock,msg,1024,0,(PSOCKADDR)&saClnt,saClntLen);
break;
case 'D':
wsprintf(msg,"D: Client form %s detachedn",inet_ntoa(saClnt.sin_addr));
pView->m_data[pView->count++]=msg;
pView->flag=TRUE;
pView->InvalidateRect(NULL);
pView->Isconnect=FALSE;
sendto(pView->m_sock,msg,1024,0,(PSOCKADDR)&saClnt,saClntLen);
break;
case 'R':
saClntLen=sizeof(saClnt);
pView->m_data[pView->count++]=msg;
pView->flag=TRUE;
pView->InvalidateRect(NULL);
break;
default:
break;
}
}
}
return(0);
}
更多精彩
赞助商链接