CRemoteOnOffDlg *PowerDlg=(CRemoteOnOffDlg*)AfxGetApp()->GetMainWnd();
while(1)
{
SockAccept=accept(PowerDlg->m_SockListen,(sockaddr*)&clientaddr,&iAddrLen);
ulClientIpAddr=clientaddr.sin_addr.s_addr;
for(int i=0;i<PowerDlg->m_ListHostInfo.GetItemCount();i++)
{
strIpAddr=PowerDlg->m_ListHostInfo.GetItemText(i,2);
if(ulClientIpAddr==inet_addr(strIpAddr))
{
PowerDlg->m_SockClient[i]=SockAccept;
//为了知道哪些客户机已建立了连接,我顺便在ListCtrll控件中对应连接客户机那一行的第五列打"√"作为标记:
PowerDlg->m_ListHostInfo.SetItemText(i,4,"√");
break;
}
}
}
}
最后在用户点击关机按钮或菜单时发送自定义的关机命令字符串:
POSITION pos=m_ListHostInfo.GetFirstSelectedItemPosition();
while(pos)
{
int nItem=m_ListHostInfo.GetNextSelectedItem(pos);//获取选择项
send(m_SockClient[nItem],"POWOFF",COM_STR_LEN,0);
closesocket(m_SockClient[nItem]);//关闭套接字
m_ListHostInfo.SetItemText(nItem,4,"×");
}
(2)客户端
先解析服务器名,然后用s o c k e t创建一个套接字,再用c o n n e c t创建与服务器的连接。最后等待接收关机命令字符串:
CString strServerIPAddr="192.168.1.1";//此处为服务端的IP地址
SOCKET SockClient;
sockaddr_in ServerSockAddr;
ServerSockAddr.sin_addr.s_addr=inet_addr(strServerIPAddr);
ServerSockAddr.sin_family=AF_INET;
ServerSockAddr.sin_port=htons(SERVER_PORT);
SockClient=socket(AF_INET,SOCK_STREAM,0);
while(connect(SockClient,(sockaddr*)&ServerSockAddr,sizeof(ServerSockAddr))!=0);
int iAllRecvLen=0,iThisRecvLen=0;
char strRecvBuf[COM_STR_LEN+1]="";
while(iThisRecvLen!=SOCKET_ERROR&&iAllRecvLen<COM_STR_LEN)
{
|