void CServerSocket::NotifyAll(CString host,CString ip,CString port,BOOL enter/* =TRUE */) { CMapStringToOb *mapSocket=&(((CCSocketDemoApp*)AfxGetApp())->mapSocket); POSITION pos; CString key; CServerSocket* tempSocket; CString msg; int ret; if(enter) msg.Format("+%s %s %s",host,ip,port); else msg.Format("#%s %s %s",host,ip,port); for(pos = mapSocket->GetStartPosition(); pos!= NULL; ) { mapSocket->GetNextAssoc(pos,key,(CObject*&)tempSocket ); ret=tempSocket->Send(CString("<?Command update client list?>")+msg,512); while(ret==SOCKET_ERROR) ret=tempSocket->Send(CString("<?Command update client list?>")+msg,512); } }
int main() { // Create the main server socket. // It is used to listen for clients CServerSocket Server; if (!Server.Create(AF_INET, SOCK_STREAM)) { cout << "Failed to create socket\n" ; return 0; } // Bind the IP address and port# to the main socket if (SOCKET_ERROR == Server.Bind("127.0.0.1", 3000)) { cout << "Failed to bind IP address to socket\n" ; return 0; } // Listen on the socket for clients to connect if (SOCKET_ERROR == Server.Listen()) { cout << "Listen on socket failed\n"; return 0; } // Create the socket to communicate with the Client CServerSocket Client; cout << "Waiting for the client to connect\n"; do { Server.Accept(Client, NULL, NULL); } while (SOCKET_ERROR == Client.GetSocket()); cout << "Client connected\n"; // Monitor the client socket for network events, such as data ready to receive Client.StartEvents(); // Send data to the client cout << "Type data to send, type quit to exit\n"; string s; for (;;) // infinite loop { getline(cin, s); if (s == "quit") break; int i = Client.Send(s.c_str(), (int)s.length(), 0); cout << "Sending " << i << " characters\n"; } return 0; }
int CListenSocket::Send(const void* lpBuf, int nBufLen, int nFlags) { // TODO: Add your specialized code here and/or call the base class POSITION pos = m_lstSvrSocket.GetHeadPosition(); while ( NULL != pos ) { CServerSocket* pSvr = m_lstSvrSocket.GetNext(pos); pSvr->Send(lpBuf,nBufLen,nFlags); } return CSocket::Send(lpBuf, nBufLen, nFlags); }
void CServerSocket::NotifyAllMembers() { CMapStringToOb *mapSocket=&(((CCSocketDemoApp*)AfxGetApp())->mapSocket); POSITION pos,pos1; CString key; CServerSocket* tempSocket; CString host,ip,port,msg,rmsg; int ret; for(pos = mapSocket->GetStartPosition(); pos!= NULL; ) { mapSocket->GetNextAssoc(pos,key,(CObject*&)tempSocket ); port.Format("%d",tempSocket->thePeerPort); msg.Format("+%s %s %s",tempSocket->host,tempSocket->thePeerIp,port); rmsg+=msg; } for(pos = mapSocket->GetStartPosition(); pos!= NULL; ) { mapSocket->GetNextAssoc(pos,key,(CObject*&)tempSocket ); ret=tempSocket->Send(CString("<?Command update client list?>")+rmsg,2048); while(ret==SOCKET_ERROR) ret=tempSocket->Send(CString("<?Command update client list?>")+rmsg,2048); } }