void CMultiSocketServer::Shutdown(const string& endpoint) { // Find the descriptor in the open socket list CServerSocket* pSocket = FindSocket(endpoint); if (pSocket) pSocket->Shutdown(); }
int main(int argc, char const *argv[]) { if(argc != 2) { cout << "\nUsage: " << argv[0] << " server_port_number" << endl; exit(0); } int portno = atoi(argv[1]); // Initialize server object CServerSocket *socket = new CServerSocket(portno); pthread_t threadID; pthread_create(&threadID, NULL, ConnectToClient, (void *)socket); pthread_join(threadID, NULL); char message[] = "hello\n"; while(1) for(auto client : socket->clients) socket->Write(client.first, message, 6); return 0; }
void CMultiSocketServer::ShutdownAll() { for (ServerSocketIterator it = m_Sockets.begin(); it != m_Sockets.end(); ++it) { CServerSocket* pSocket = it->second; pSocket->Shutdown(); } }
void CListenerSocket::incomingConnection(qintptr socketDescriptor) { CServerSocket * pSock = new CServerSocket(); pSock->setSocketDescriptor(socketDescriptor); connect(pSock,SIGNAL(MessageReady(QString)),this,SLOT(OnIncomingMessage(QString))); serverSockets.push_back(pSock); addPendingConnection(pSock); nextPendingConnection(); }
// TODO: If anyone tries to access this list now...things will be bad... void CMultiSocketServer::CloseAll() { for (ServerSocketIterator it = m_Sockets.begin(); it != m_Sockets.end(); ++it) { CServerSocket* pSocket = it->second; // TODO: Make sure it is Shutdown() first??? pSocket->Close(); delete pSocket; } m_Sockets.clear(); }
// TODO: Synchronize list operations? void CMultiSocketServer::Close(const string& endpoint) { // Find the descriptor in the open socket list CServerSocket* pSocket = FindSocket(endpoint); if (pSocket) { m_Sockets.erase(endpoint); pSocket->Close(); delete pSocket; } }
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); }
DWORD WINAPI AcceptThreadFunc(LPVOID lpThreadParameter) { CServerSocket* Server = (CServerSocket*) lpThreadParameter; while (!Server->IsTerminated()) { // Wait until the socket is listening // TODO: This takes a lot of time! Should be removed to increase performance Server->WaitIsListening(); // Now get handling them new clients Server->AcceptClient(); } return 0; }
void *ConnectToClient(void* server) { CServerSocket *serverObj = static_cast<CServerSocket *>(server); while(1) { cout << "Waiting for new client\n"; if(serverObj->ConnectClient()) cout << "Connected to client and assigned id: " << serverObj->clientId - 1 << endl; else cout << "Cannot connect to client\n"; } pthread_exit(NULL); }
void CServerConnect::ConnectToServer(CServer* server, bool multiconnect, bool bNoCrypt) { if (!multiconnect) { StopConnectionTry(); Disconnect(); } connecting = true; singleconnecting = !multiconnect; theApp.emuledlg->ShowConnectionState(); CServerSocket* newsocket = new CServerSocket(this, !multiconnect); m_lstOpenSockets.AddTail((void*&)newsocket); newsocket->Create(0, SOCK_STREAM, FD_READ | FD_WRITE | FD_CLOSE | FD_CONNECT, thePrefs.GetBindAddrA()); newsocket->ConnectTo(server, bNoCrypt); connectionattemps.SetAt(GetTickCount(), newsocket); }
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; }
unsigned int __stdcall CServerSocket::WorkerThread( LPVOID lp ) { int result = 0 ; CServerSocket * pthis = (CServerSocket*)lp ; if( pthis ) { try { result = pthis->Worker() ; } catch ( ... ) { ::PrintConsole( "[EXCEPTION]Worker\n" ) ; } } return result ; }
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); } }
void CListenSocket::OnAccept(int nErrorCode) { // TODO: Add your specialized code here and/or call the base class CServerSocket* pSvr = new CServerSocket; CSocket::Accept(*pSvr); pSvr->m_pMainWnd = m_pMainWnd; CString strPear; UINT nPort; pSvr->GetPeerName(strPear, nPort); m_lstSvrSocket.AddTail(pSvr); OutputDebugString("-------------------------------------------------\r\n"); OutputDebugString("*************************************************\r\n"); /* // Keep Alive SOCKET sock = pSvr->m_hSocket; tcp_keepalive inKeepAlive = {0}; // 输入参数 unsigned long ulInLen = sizeof(tcp_keepalive); tcp_keepalive outKeepAlive = {0}; // 输出参数 unsigned long ulOutLen = sizeof(tcp_keepalive); unsigned long ulBytesReturn = 0; // 设置socket的keep alive为5秒,并且发送次数为3次 inKeepAlive.onoff = 1; inKeepAlive.keepaliveinterval = 1000; // 两次KeepAlive探测间的时间间隔 inKeepAlive.keepalivetime = 5000; // 开始首次KeepAlive探测前的TCP空闭时间 if (WSAIoctl(sock, SIO_KEEPALIVE_VALS, (LPVOID)&inKeepAlive, ulInLen, (LPVOID)&outKeepAlive, ulOutLen, &ulBytesReturn, NULL, NULL) == SOCKET_ERROR) { return; // return 0; } */ CSocket::OnAccept(nErrorCode); }
// true if the IP is one of a server which we currently try to connect to bool CServerConnect::AwaitingTestFromIP(uint32 dwIP) const{ if (connectionattemps.IsEmpty()) return false; DWORD tmpkey; CServerSocket* tmpsock; POSITION pos = connectionattemps.GetStartPosition(); while (pos) { connectionattemps.GetNextAssoc(pos, tmpkey, tmpsock); if (tmpsock != NULL && tmpsock->cur_server != NULL && tmpsock->cur_server->GetIP() == dwIP && tmpsock->GetConnectionState() == CS_WAITFORLOGIN) return true; } return false; }
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); } }
DWORD WINAPI ThreadRecv(PVOID param) { CServerSocket *Server = (CServerSocket*)param; int bytesRecv = SOCKET_ERROR; char recvbuf[8192] = {0}; //接收区 DWORD dwPackteCount = 0; char *pDataBuff = NULL; //缓冲区 DWORD dwDataBuffLen = 0; //缓冲区长度 Server->WaitClient(); while(Server->m_bRun) { bytesRecv = recv( Server->m_ClientSocket, recvbuf, 8192, 0 ); g_log.Trace(LOGL_TOP,LOGT_PROMPT,__TFILE__, __LINE__,_T("收到控件发过来的数据,数据大小:%d"), bytesRecv); if( bytesRecv == -1 || bytesRecv == 0) //客户端断开连接 { Server->m_ClientSocket = INVALID_SOCKET ; g_log.Trace(LOGL_TOP,LOGT_PROMPT,__TFILE__, __LINE__,_T("客户端断开连接,退出任务")); return 0; //退出程序 } if(pDataBuff == NULL) { pDataBuff = new char[bytesRecv]; memcpy(pDataBuff,recvbuf,bytesRecv); dwDataBuffLen = bytesRecv; } else { char *tmpBuff = new char[dwDataBuffLen]; memcpy(tmpBuff,pDataBuff,dwDataBuffLen); delete []pDataBuff; pDataBuff = new char[dwDataBuffLen + bytesRecv]; memcpy(pDataBuff,tmpBuff,dwDataBuffLen); delete []tmpBuff; memcpy(&(pDataBuff[dwDataBuffLen]),recvbuf,bytesRecv); dwDataBuffLen += bytesRecv; } //包处理 if(dwDataBuffLen<sizeof(DWORD)*2)continue; //小于最小包头不做如下处理 DWORD dwPacketSize = 0; //包大小 while(TRUE) { if(dwDataBuffLen == 0)break; //缓冲区没有数据 memcpy(&dwPacketSize,pDataBuff,sizeof(DWORD)); if(dwPacketSize > dwDataBuffLen) break; //包长度大于缓冲区长度不做处理 char *pData = new char[dwPacketSize]; //拼一个包 memcpy(pData,pDataBuff,dwPacketSize); Server->m_ProcessData.CovertBufData(pData,dwPacketSize); delete []pData; char *tmpBuff = new char[dwDataBuffLen]; memcpy(tmpBuff,pDataBuff,dwDataBuffLen); delete []pDataBuff; dwDataBuffLen = dwDataBuffLen - dwPacketSize; pDataBuff = new char[dwDataBuffLen]; memcpy(pDataBuff,&(tmpBuff[dwPacketSize]),dwDataBuffLen); delete []tmpBuff; dwPackteCount ++ ; //包计数器 } printf("总共收到数据包 %d\n",dwPackteCount); //包计数器 Sleep(200); //线程切换 } return 0; }