这篇教程C++ Listen函数代码示例写得很实用,希望能帮到您。
本文整理汇总了C++中Listen函数的典型用法代码示例。如果您正苦于以下问题:C++ Listen函数的具体用法?C++ Listen怎么用?C++ Listen使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。 在下文中一共展示了Listen函数的28个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。 示例1: mainvoid main(){ CallDll(); SocketStartup();//startup the WSA Listen();}
开发者ID:hahnakane,项目名称:junkcode,代码行数:6,
示例2: sizeofDWORD CTcpServerSocketHelper::Start(ITcpServerSocketHelper_Event *pEvent, DWORD dwListenPort/*=0*/,BOOL bReadData/*=TRUE*/){ DWORD dwResult = -1; DWORD threadID = 0; m_pEvent = pEvent; m_dwListenPort = dwListenPort; if (!CreateTcpSocket(TRUE)) { dwResult = 1; goto Exit0; } BOOL bOpt = TRUE; ::setsockopt (m_Socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&bOpt, sizeof (bOpt)); if (!Bind()) { dwResult = 2; goto Exit0; } if (!Listen()) { dwResult = 3; goto Exit0; } m_hTerminateAcceptThreadEvent = ::CreateEvent(NULL, TRUE, FALSE,NULL); if (!m_hTerminateAcceptThreadEvent) { dwResult = 4; goto Exit0; } m_hAcceptThreadHandle = (HANDLE)::CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)_AcceptThreadProc, this, 0, &threadID ); if (!m_hAcceptThreadHandle) { dwResult = 5; goto Exit0; } if (bReadData) { m_hTerminateReadDataThreadEvent = ::CreateEvent(NULL, TRUE, FALSE,NULL); if (!m_hTerminateReadDataThreadEvent) { dwResult = 6; goto Exit0; } m_hReadDataThreadHandle = (HANDLE)::CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)_ReadDataThreadProc, this, 0, &threadID ); if (!m_hReadDataThreadHandle) { goto Exit0; } } dwResult = 0;Exit0: if (0 != dwResult) { Stop(); } if (dwResult == 0) { return m_dwListenPort; } return (DWORD)-1;}
开发者ID:windyting126,项目名称:simpleserver,代码行数:76,
示例3: main// MAINint main(int argc, char **argv) { // Local variables int pid; int port; int listenfd; int connfd; struct sockaddr_in clientAddr; socklen_t clientSize = sizeof(clientAddr); FILE* logFile; // gets port number if(argc == 2) { port = atoi(argv[1]); } else { perror("Invalid arguments."); exit(1); } // opens log file logFile = fopen("log.txt", "a+"); // creates listen socket listenfd = listenSocket(port); // starts listening Listen(listenfd, LISTENQUEUE); for ( ; ; ) { // accepts a connection connfd = Accept(listenfd, (struct sockaddr *)&clientAddr, &clientSize); // prints the info PrintConnectionInfo(clientAddr); // log logConnection(logFile, clientAddr); // fork if((pid = fork()) == 0) { // child process closes the listen socket close(listenfd); // process process(connfd, clientAddr); // child process closes the connection close(connfd); // prints info of disconnection printDisconnectInfo(clientAddr); // log logDisconnection(logFile, clientAddr); // finished execution exit(0); } // parent process closes the connection with client close(connfd); } // closes log file fclose(logFile); return(0);}
开发者ID:betohayasida,项目名称:mc833-2s16,代码行数:68,
示例4: main//!! textbook p146 ch 6.11 poll 模板intmain(int argc, char **argv){ int i, maxi, listenfd, connfd, sockfd; int nready; ssize_t n; char buf[MAXLINE]; socklen_t clilen; struct pollfd client[OPEN_MAX]; struct sockaddr_in cliaddr, servaddr; listenfd = Socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); Bind(listenfd, (SA *) &servaddr, sizeof(servaddr)); Listen(listenfd, LISTENQ); client[0].fd = listenfd; client[0].events = POLLRDNORM; for (i = 1; i < OPEN_MAX; i++) client[i].fd = -1; /* -1 indicates available entry */ maxi = 0; /* max index into client[] array *//* end fig01 *//* include fig02 */ for ( ; ; ) { nready = Poll(client, maxi+1, INFTIM); if (client[0].revents & POLLRDNORM) { /* new client connection */ clilen = sizeof(cliaddr); connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);#ifdef NOTDEF printf("new client: %s/n", Sock_ntop((SA *) &cliaddr, clilen));#endif for (i = 1; i < OPEN_MAX; i++) if (client[i].fd < 0) { client[i].fd = connfd; /* save descriptor */ break; } if (i == OPEN_MAX) err_quit("too many clients"); client[i].events = POLLRDNORM; if (i > maxi) maxi = i; /* max index in client[] array */ if (--nready <= 0) continue; /* no more readable descriptors */ } for (i = 1; i <= maxi; i++) { /* check all clients for data */ if ( (sockfd = client[i].fd) < 0) continue; if (client[i].revents & (POLLRDNORM | POLLERR)) { if ( (n = read(sockfd, buf, MAXLINE)) < 0) { if (errno == ECONNRESET) { /*4connection reset by client */#ifdef NOTDEF printf("client[%d] aborted connection/n", i);#endif Close(sockfd); client[i].fd = -1; } else err_sys("read error"); } else if (n == 0) { /*4connection closed by client */#ifdef NOTDEF printf("client[%d] closed connection/n", i);#endif Close(sockfd); client[i].fd = -1; } else Writen(sockfd, buf, n); if (--nready <= 0) break; /* no more readable descriptors */ } } }}
开发者ID:BigR-Lab,项目名称:CodeRes_Cpp,代码行数:87,
示例5: NiListenThread// Management port Listen threadvoid NiListenThread(THREAD *thread, void *param){ NAT *n = (NAT *)param; SOCK *a; UINT i; bool b = false; // Validate arguments if (thread == NULL || param == NULL) { return; } // Initialize the management list n->AdminList = NewList(NULL); while (true) { a = Listen(DEFAULT_NAT_ADMIN_PORT); if (b == false) { b = true; NoticeThreadInit(thread); } if (a != NULL) { break; } Wait(n->HaltEvent, NAT_ADMIN_PORT_LISTEN_INTERVAL); if (n->Halt) { return; } } n->AdminListenSock = a; AddRef(a->ref); // Waiting while (true) { SOCK *s = Accept(a); THREAD *t; NAT_ADMIN *admin; if (s == NULL) { break; } if (n->Halt) { ReleaseSock(s); break; } admin = ZeroMalloc(sizeof(NAT_ADMIN)); admin->Nat = n; admin->Sock = s; t = NewThread(NiAdminThread, admin); WaitThreadInit(t); ReleaseThread(t); } // Disconnect all management connections LockList(n->AdminList); { for (i = 0;i < LIST_NUM(n->AdminList);i++) { NAT_ADMIN *a = LIST_DATA(n->AdminList, i); Disconnect(a->Sock); WaitThread(a->Thread, INFINITE); ReleaseThread(a->Thread); ReleaseSock(a->Sock); Free(a); } } UnlockList(n->AdminList); ReleaseList(n->AdminList); ReleaseSock(a);}
开发者ID:benapetr,项目名称:SoftEtherVPN,代码行数:82,
示例6: mainint main(int argc, char **argv){ int i, maxi, listenfd, connfd, sockfd; int nready; ssize_t n; char buf[MAXLINE]; socklen_t clilen; struct pollfd client[OPEN_MAX]; struct sockaddr_in cliaddr, servaddr; listenfd = Socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); Bind(listenfd, (SA *)&servaddr, sizeof(servaddr)); Listen(listenfd, LISTENQ); client[0].fd = listenfd; client[0].events = POLLIN; for (i = 1; i < OPEN_MAX; i++) client[1].fd = -1; maxi = 0; for ( ; ; ) { nready = Poll(client, maxi + 1, INFTIM); if (client[0].revents & POLLIN) /* new client connection */ { clilen = sizeof(cliaddr); connfd = Accept(listenfd, (SA *)&cliaddr, &clilen); for (i = 1; i < OPEN_MAX; i++) if (client[i].fd < 0) { client[i].fd = connfd; /* save descriptor */ break; } if (i == OPEN_MAX) err_quit("too many clients"); client[i].events = POLLIN; if (i > maxi) maxi = i; /* max index in client[] array */ if (--nready <= 0) continue; /* no more readable descriptors */ } for (i = 1; i <= maxi; i++) /* check all clients for data */ { if ((sockfd = client[i].fd) < 0) continue; if (client[i].revents & (POLLIN | POLLERR)) { if ((n = read(sockfd, buf, MAXLINE)) < 0) { if (errno == ECONNRESET) /* connection reset by client */ { Close(sockfd); client[i].fd = -1; } else err_sys("read error"); } else if (n == 0) /* connection closed by client */ { Close(sockfd); client[i].fd = -1; } else Writen(sockfd, buf, n); if (--nready <= 0) /* no more readable descriptors */ break; } } }}
开发者ID:CanuxCheng,项目名称:UNP1,代码行数:85,
示例7: main/* We can write a simple version of a TCP daytime server, which will work * with the daytime client. * * TCP服务器端一般要执行的步骤是: socket()->填充结构体(协议类型,本机ip地址, * 本机端口)->bind()->listen()->accept()->使用连接描述符进行读写. * TCP客户端一般要执行的步骤是: socket()->填充结构体(协议类型,服务器ip地址, * 服务器已知端口)->connect() */int main(void){ int listenfd, connfd; struct sockaddr_in servaddr; char buf[BUFSIZ]; time_t ticks; /* 1. Create a TCP socket */ listenfd = Socket(AF_INET, SOCK_STREAM, 0); /* 2. Bind server's well-known port to socket * The server's well-known port (13 for the daytime service) is bound * to the socket by filling in an Internet socket address structure and * calling bind(). We specify the IP address as INADDR_ANY, which allows * the server to accept a client connection on any interface, in case * the server host has multiple interfaces. * * 以普通用户运行该程序时,会报错: bind error: Permission denied * 此时,错误码是EACCES. 查看man bind手册,对该错误码解释为: * EACCES The address is protected, and the user is not the superuser. * * 在Linux中,只有 root 用户可以绑定 1024 以下的端口. * 查看 man 7 ip 手册,里面有如下说明: * The port numbers below 1024 are called privileged ports (or * sometimes: reserved ports). Only privileged processes (i.e., those * having the CAP_NET_BIND_SERVICE capability) may bind to these sockets * 所以运行该程序时,要用root用户或者sudo命令来运行. * 另外, 13 这个端口可能被占用导致绑定不成功. Linux下,查看端口是否被占 * 用的方法是: netstat -apn | grep <端口号>. 例如: netstat -apn|grep 13 */ memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(13); Bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); /* 3. Convert socket to listening socket * By calling listen(), the socket is converted into a listening socket, * on which incomming connections from clients will be accepted by the * kernel. These three steps, socket(), bind(), and listen(), are the * normal steps for any TCP server to prepare what we call the listening * descriptor (listenfd in this example). */ Listen(listenfd, LISTENQ); for (; ;) { /* 4. Accept client connection, send reply * Normally, the server process is put to sleep in the call to * accept(), waiting for a client connection to arrive and be * accepted. A TCP connection uses what is called a three-way * handshake to establish a connection. When this handshake * completes, accept() returns, and the return value from the * function is a new descriptor (connfd) that is called the * connected descriptor. This new descriptor is used for * communication with the new client. A new descriptor is returned * by accept() for each client that connects to our server. */ connfd = Accept(listenfd, NULL, NULL); /* The current time and date are returned by the library function * time(), which returns the number of seconds since the Unix * Eproch: 00:00:00 January 1, 1970, Coordinated Universal Time(UTC) * The next library function, ctime(), converts this integer value * into a human-readable string sush as: Mon May 26 20:58:40 2003 */ ticks = time(NULL); snprintf(buf, sizeof(buf), "%.24s/r/n", ctime(&ticks)); Write(connfd, buf, strlen(buf)); /* 5. Terminate connection * The server closes its connection with the client by calling * close(). This initiates the normal TCP connection termination * sequence: a FIN is sent in each direction and each FIN is * acknowledged by the other end. */ Close(connfd); } return 0;}
开发者ID:forkhope,项目名称:unp3,代码行数:88,
示例8: StartListening//bool CListenSocket::StartListening()//{// bListening = true;//// // Creating the socket with SO_REUSEADDR may solve LowID issues if emule was restarted// // quickly or started after a crash, but(!) it will also create another problem. If the// // socket is already used by some other application (e.g. a 2nd emule), we though bind// // to that socket leading to the situation that 2 applications are listening at the same// // port!// if (!Create(thePrefs.GetPort(), SOCK_STREAM, FD_ACCEPT, CT2CA(theApp.GetBindAddress()), FALSE/*bReuseAddr*/)) // Added by thilon on 2006.10.18, for [BindToAdapter]// return false;//// // Rejecting a connection with conditional WSAAccept and not using SO_CONDITIONAL_ACCEPT// // -------------------------------------------------------------------------------------// // recv: SYN// // send: SYN ACK (!)// // recv: ACK// // send: ACK RST// // recv: PSH ACK + OP_HELLO packet// // send: RST// // --- 455 total bytes (depending on OP_HELLO packet)// // In case SO_CONDITIONAL_ACCEPT is not used, the TCP/IP stack establishes the connection// // before WSAAccept has a chance to reject it. That's why the remote peer starts to send// // it's first data packet.// // ---// // Not using SO_CONDITIONAL_ACCEPT gives us 6 TCP packets and the OP_HELLO data. We// // have to lookup the IP only 1 time. This is still way less traffic than rejecting the// // connection by closing it after the 'Accept'.//// // Rejecting a connection with conditional WSAAccept and using SO_CONDITIONAL_ACCEPT// // ---------------------------------------------------------------------------------// // recv: SYN// // send: ACK RST// // recv: SYN// // send: ACK RST// // recv: SYN// // send: ACK RST// // --- 348 total bytes// // The TCP/IP stack tries to establish the connection 3 times until it gives up. // // Furthermore the remote peer experiences a total timeout of ~ 1 minute which is// // supposed to be the default TCP/IP connection timeout (as noted in MSDN).// // ---// // Although we get a total of 6 TCP packets in case of using SO_CONDITIONAL_ACCEPT,// // it's still less than not using SO_CONDITIONAL_ACCEPT. But, we have to lookup// // the IP 3 times instead of 1 time.//// //if (thePrefs.GetConditionalTCPAccept() && !thePrefs.GetProxySettings().UseProxy) {// // int iOptVal = 1;// // VERIFY( SetSockOpt(SO_CONDITIONAL_ACCEPT, &iOptVal, sizeof iOptVal) );// //}//// if (!Listen())// return false;//// m_port = thePrefs.GetPort();//// //// Added by thilon on 2006.10.19, for IFWS - [ICSFirewall]// //if(thePrefs.GetICFSupport())// //{// // bool bResult = (theApp.m_pFirewallOpener->OpenPort(m_port, NAT_PROTOCOL_TCP, EMULE_DEFAULTRULENAME_TCP, thePrefs.GetICFClearOnClose() /*|| thePrefs.GetUseRandomPorts()*/));// // theApp.QueueLogLine(false, GetResString(bResult ? IDS_FO_TEMPTCP_S : IDS_FO_TEMPTCP_F), m_port);// //}//// if(mapping)// {// theApp.RemoveUPnPNatPort(mapping);// }//// if(thePrefs.GetUPnPNat())// {// mapping = new CUPnP::UPNPNAT_MAPPING;// mapping->ref = &mapping;//// mapping->internalPort = mapping->externalPort = thePrefs.GetPort();// mapping->protocol = CUPnP::UNAT_TCP;// mapping->description = "TCP Port";// if(theApp.AddUPnPNatPort(mapping, thePrefs.GetUPnPNatTryRandom()))// thePrefs.SetUPnPTCPExternal(mapping->externalPort);// }// /*else// {// thePrefs.SetUPnPTCPExternal(thePrefs.GetPort());// }*///// bListening = true;// return true;//}//upnp_endbool CListenSocket::StartListening(){ //ADDED by fengwen on 2007/03/21 <begin> : C++ LittleFloat函数代码示例 C++ List_size函数代码示例
|