BOOL CNetManager::Start( IDataHandler *pBufferHandler ) { if(pBufferHandler == NULL) { ASSERT_FAIELD; return FALSE; } m_pBufferHandler = pBufferHandler; if(!InitNetwork()) { ASSERT_FAIELD; CLog::GetInstancePtr()->AddLog("初始化网络失败!!"); return FALSE; } if(!CreateCompletePort()) { ASSERT_FAIELD; CLog::GetInstancePtr()->AddLog("创建完成端口或Epoll失败!!"); return FALSE; } if(!CreateEventThread(0)) { ASSERT_FAIELD; CLog::GetInstancePtr()->AddLog("创建网络事件处理线程失败!!"); return FALSE; } if(!CreateDispatchThread()) { ASSERT_FAIELD; CLog::GetInstancePtr()->AddLog("创建事件分发线程失败!!"); return FALSE; } if(!CreateSendDataThread()) { ASSERT_FAIELD; CLog::GetInstancePtr()->AddLog("创建数据发送线程失败!!"); return FALSE; } if(!StartListen()) { ASSERT_FAIELD; CLog::GetInstancePtr()->AddLog("开启监听失败!!"); return FALSE; } return TRUE; }
void CLan::SetCurHostAddress(in_addr addr) { if (m_mode!=LM_OFF) { int oldMode = m_mode; StopListen(); m_curAddr = addr; if (oldMode==LM_LISTEN) StartListen(); } }
//启动服务器聚合‘event timeout’类型不完全,无法被定义 bool MMaster::Run() { do { if (!InitWorkerThreads()) break; if (!StartListen()) break; return true; } while (0); return false; }
void SocketTestWindow::on_m_pbListen_clicked() { m_tcpEnable = ui->m_rbTcpEnable->isChecked(); m_udpEnable = !m_tcpEnable; StartListen(); if(m_startFlags) { ui->m_pbConnect->setEnabled(false); ui->m_pbListen->setEnabled(false); ui->m_rbUdpEnable->setEnabled(false); ui->m_rbTcpEnable->setEnabled(false); ui->m_pbDisconnect->setEnabled(true); } }
void CMLan::StartChecking() { if (m_hCheckThread) return; TContact* cont = m_pRootContact; while (cont) { cont->m_time = MLAN_CHECK + MLAN_TIMEOUT; cont = cont->m_prev; } DWORD threadId; m_hCheckThread = CreateThread(NULL, 0, CheckProc, (LPVOID)this, 0, &threadId); StartListen(); RequestStatus(true); }
LRESULT CALLBACK WndProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_SOCKET: { switch (WSAGETSELECTEVENT(lParam)) { case FD_READ: { // Look pointer to Client using wParam (Socket) Client *pClient = NULL; if (Clients.find((SOCKET)wParam) != Clients.end()) pClient = Clients[(SOCKET)wParam]; // Retrieve data available char Buffer[BUFFER_LENGTH]; int BufferLength = recv((SOCKET)wParam, Buffer, BUFFER_LENGTH, 0); if (BufferLength) { // Create Data variable and fill with unprocessed data and new data std::vector<char> Data(pClient->Buffer); Data.insert(Data.end(), Buffer, Buffer + BufferLength); do { // Get length of current packet DWORD PacketLength; memcpy(&PacketLength, &Data[1], 4); /* If length of buffer now exceeds or is equal to size of packet, then / process the packet. Otherwise keep appending newly received / data until a full packet has been accumlated. */ if (Data.size() >= (int)PacketLength) { // Parse packet data to Client class Packet CurrentPacket(std::vector<char>(Data.begin(), Data.begin() + (int)PacketLength)); pClient->ParsePacket(CurrentPacket); // Erase Packet from remaining data Data.erase(Data.begin(), Data.begin() + (int)PacketLength); // Clear Client's buffered data pClient->Buffer.clear(); } else { // If not enough data for a complete packet, add remaining data to Client's buffer pClient->Buffer.clear(); pClient->Buffer = Data; Data.clear(); } } while (!Data.empty()); } } break; case FD_CLOSE: { // Look up pointer to Client using wParam (Socket) Client *pClient = NULL; if (Clients.find((SOCKET)wParam) != Clients.end()) pClient = Clients[(SOCKET)wParam]; // Delete Client delete pClient; } break; case FD_ACCEPT: { if (wParam == SocketListen) { // Create new Client Client *NewClient = new Client(SocketListen); Clients[NewClient->Socket()] = NewClient; } } break; case FD_WRITE: // break; case FD_CONNECT: // break; default: ; } } break; case WM_COMMAND: { if (LOWORD(wParam) == (WORD)IDM_START) { // Create 'imgs' directory to store files if doesn't already exists CreateImageDirectory(); // Get port from textbox int Length = SendMessage(tPort, WM_GETTEXTLENGTH, NULL, NULL); std::wstring Text; if (Length > 0) { std::vector<WCHAR> Buffer(Length + 1); SendMessage(tPort, WM_GETTEXT, Buffer.size(), (LPARAM)&Buffer[0]); Text = &Buffer[0]; } // Convert variable types wstring -> string -> int std::string Port(Text.begin(), Text.end()); int iStartListen = StartListen(atoi(Port.c_str())); if (iStartListen) { EnableWindow(lPort, (int)false); EnableWindow(tPort, (int)false); EnableWindow(bStart, (int)false); EnableWindow(bClose, (int)true); std::wstringstream wsPort; wsPort << iStartListen; SendMessage(tPort, WM_SETTEXT, NULL, (LPARAM)wsPort.str().c_str()); AddLog(L"Server listening on " + GetLocalIP() + L" using port " + wsPort.str().c_str() + L"."); } else AddLog(L"Failed to start server."); } else if (LOWORD(wParam) == (WORD)IDM_CLOSE) { CloseWinsock(); EnableWindow(bClose, (int)false); EnableWindow(lPort, (int)true); EnableWindow(tPort, (int)true); EnableWindow(bStart, (int)true); SendMessage(lsClients, LB_RESETCONTENT, 0, 0); SendMessage(lsFiles, LB_RESETCONTENT, 0, 0); for (int i = 0; i < USERS_COUNT;) Users[i++].LoggedIn = false; std::list<File *>::iterator itFile = Files.begin(); // Clear file list and clear remaining objects while (itFile != Files.end()) delete *itFile++; Files.clear(); AddLog(L"Server closed."); } } break; case WM_CREATE: { // Set hWnd here as WM_CREATE executes before CreateWindowEx() returns fMain = hWnd; // Start window center screen RECT Rect; if (GetWindowRect(hWnd, &Rect)) { int Width, Height, Left, Top; Width = Rect.right - Rect.left; Height = Rect.bottom - Rect.top; Left = (GetSystemMetrics(SM_CXSCREEN) - Width) / 2; Top = (GetSystemMetrics(SM_CYSCREEN) - Height) / 2; SetWindowPos(hWnd, NULL, Left, Top, NULL, NULL, SWP_NOZORDER | SWP_NOSIZE); } // Create controls lPort = CreateWindow(L"EDIT", L"Port:", DefaultStyles | ES_RIGHT, 16, 16, 33, 25, hWnd, 0, 0, 0); if (lPort) SetFont(lPort); tPort = CreateWindowEx(WS_EX_CLIENTEDGE, L"Edit", L"80", DefaultStyles | ES_NUMBER, 56, 16, 81, 24, hWnd, 0, WinInstance, 0); if (tPort) { SetFont(tPort); SendMessage(tPort, EM_LIMITTEXT, (WPARAM)5, NULL); // Set max length to 5 characters } bStart = CreateWindowEx(0, L"Button", L"&Start Server", DefaultStyles, 144, 8, 113, 33, hWnd, IDM_START, WinInstance, NULL); if (bStart) SetFont(bStart); bClose = CreateWindowEx(0, L"Button", L"&Close Server", DefaultStyles | WS_DISABLED, 264, 8, 113, 33, hWnd, IDM_CLOSE, WinInstance, NULL); if (bClose) SetFont(bClose); tLog = CreateWindowEx(WS_EX_CLIENTEDGE, L"Edit", L"", DefaultStyles | ES_READONLY | ES_MULTILINE | WS_VSCROLL | ES_AUTOVSCROLL, 16, 48, 450, 344, hWnd, 0, WinInstance, 0); if (tLog) SetFont(tLog); lsClients = CreateWindowEx(WS_EX_CLIENTEDGE, L"Listbox", L"", DefaultStyles | WS_VSCROLL, 480, 48, 376, 280, hWnd, 0, WinInstance, 0); if (lsClients) SetFont(lsClients); lsFiles = CreateWindowEx(WS_EX_CLIENTEDGE, L"Listbox", L"", DefaultStyles | WS_VSCROLL, 16, 400, 840, 220, hWnd, 0, WinInstance, 0); if (lsFiles) SetFont(lsFiles); } break; case WM_CLOSE: DestroyWindow(hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, Message, wParam, lParam); } return 0; }
void NNTPListener::run() { int rval; fd_set readfs; struct timeval tv; std::vector<SOCKET>::iterator listeni; SOCKET highsocket; m_log->debug("NNTPListener::run thread started."); try { LoadDatabase(m_log); StartListen(); do { // reset values highsocket=0; tv.tv_sec=1; tv.tv_usec=0; // clear fd set FD_ZERO(&readfs); // put all listen sockets on the fd set for(listeni=m_listensockets.begin(); listeni!=m_listensockets.end(); ++listeni) { FD_SET((*listeni),&readfs); if((*listeni)>highsocket) { highsocket=(*listeni); } } // see if any connections are waiting rval=select(highsocket+1,&readfs,0,0,&tv); // check for new connections if(rval>0) { for(listeni=m_listensockets.begin(); listeni!=m_listensockets.end(); ++listeni) { if(FD_ISSET((*listeni),&readfs)) { SOCKET newsock; struct sockaddr_storage addr; socklen_t addrlen=sizeof(addr); newsock=accept((*listeni),(struct sockaddr *)&addr,&addrlen); m_log->information("NNTPListener::run NNTP client connected"); m_connections.Start(new NNTPConnection(newsock),"NNTPConnection"); } } } }while(!IsCancelled() && m_listensockets.size()>0); m_connections.Cancel(); m_connections.Join(); for(listeni=m_listensockets.begin(); listeni!=m_listensockets.end(); ++listeni) { #ifdef _WIN32 closesocket((*listeni)); #else close((*listeni)); #endif } m_listensockets.clear(); } catch(SQLite3DB::Exception &e) { m_log->fatal("NNTPListener caught SQLite3DB::Exception "+e.what()); ((FMSApp *)&FMSApp::instance())->Terminate(); } m_log->debug("NNTPListener::run thread exiting."); }
BOOL CDOSObjectProxyService::OnStart() { FUNCTION_BEGIN; m_ThreadPerformanceCounter.Init(GetThreadHandle(),THREAD_CPU_COUNT_TIME); if(!m_ConnectionPool.Create(((CDOSServer *)GetServer())->GetConfig().MaxProxyConnection)) { PrintDOSLog(0xff0000,_T("创建%u大小的连接池失败!"), ((CDOSServer *)GetServer())->GetConfig().MaxProxyConnection); return FALSE; } if(!m_MsgQueue.Create(((CDOSServer *)GetServer())->GetConfig().MaxProxyMsgQueue)) { PrintDOSLog(0xff0000,_T("创建%u大小的消息队列失败!"), ((CDOSServer *)GetServer())->GetConfig().MaxProxyMsgQueue); return FALSE; } if(!m_MessageMap.Create(((CDOSServer *)GetServer())->GetConfig().MaxProxyGlobalMsgMap)) { PrintDOSLog(0xff0000,_T("创建%u大小的消息映射表失败!"), ((CDOSServer *)GetServer())->GetConfig().MaxProxyGlobalMsgMap); return FALSE; } if(((CDOSServer *)GetServer())->GetConfig().ProxyMsgMinCompressSize) { if (lzo_init() != LZO_E_OK) { PrintDOSLog(0xff0000,_T("代理服务开启消息压缩失败")); return FALSE; } PrintDOSDebugLog(0xff0000,_T("代理服务开启消息压缩")); } if(!Create(IPPROTO_TCP, DEFAULT_SERVER_ACCEPT_QUEUE, DEFAULT_SERVER_RECV_DATA_QUEUE, ((CDOSServer *)GetServer())->GetConfig().ProxySendBufferSize, DEFAULT_PARALLEL_ACCEPT, DEFAULT_PARALLEL_RECV, false)) { PrintDOSLog(0xffff,_T("代理服务创建失败!")); return FALSE; } if(!StartListen(((CDOSServer *)GetServer())->GetConfig().ObjectProxyServiceListenAddress)) { PrintDOSLog(0xffff,_T("代理服务侦听于(%s:%u)失败!"), ((CDOSServer *)GetServer())->GetConfig().ObjectProxyServiceListenAddress.GetIPString(), ((CDOSServer *)GetServer())->GetConfig().ObjectProxyServiceListenAddress.GetPort()); return FALSE; } PrintDOSLog(0xffff,_T("代理服务侦听于(%s:%u)!"), ((CDOSServer *)GetServer())->GetConfig().ObjectProxyServiceListenAddress.GetIPString(), ((CDOSServer *)GetServer())->GetConfig().ObjectProxyServiceListenAddress.GetPort()); PrintDOSLog(0xff0000,_T("对象代理线程[%u]已启动"),GetThreadID()); return TRUE; FUNCTION_END; return FALSE; }
bool tconn::run() { if(!StartListen()) return false; struct epoll_event events[EPOLL_MAX_EVENTS]; while (true) { bool working=false; int rv=epoll_wait(epollfd,events,EPOLL_MAX_EVENTS,0); if(rv>0) { working=true; INFO("epoll_wait,receive event%d",rv); for(int i=0; i<rv; i++) { unsigned int pos=events[i].data.u32; DEBUG("epoll event pos|%d",pos); if(pos==EPOLL_LISTEN_POS) { if(events[i].events&EPOLLIN) AcceptTask(); else WARN("Listen socket receive event:%d",events[i].events); } else { TaskPtr task=FindTask(pos); if(!task) { WARN("not find client task,pos:%d",pos); continue; } if(events[i].events&EPOLLIN) { DEBUG("recv client package"); task->Recv(); } if(events[i].events&EPOLLOUT) task->Send(); if(events[i].events&EPOLLERR) { task->Terminate(); continue; } if(events[i].events&EPOLLRDHUP) { task->Terminate(); continue; } } } } else { if(rv==-1) { if(errno==EINTR) { INFO("epoll_wait no events"); } else { WARN("epoll_wait failed|%d|%s",errno,strerror(errno)); continue; } } } if(!working) usleep(1000); } }