accept()是在一個套接口接受的一個連線。accept()是c語言中網路編程的重要的函式,本函式從s的等待連線佇列中抽取第一個連線,創建一個與s同類的新的套接口並返回句柄。
基本介紹
- 外文名:accept()
- 檔案包含:#include <sys/socket.h>
- 原型:SOCKET accept()
- 返回值:失敗:INVALID_SOCKET
表達式簡介
例子(c++)
#ifndef UNICODE #defineUNICODE#endif#include <stdio.h>#ifdef WIN32#include <winsock2.h> #include <windows.h>
//NeedtolinkwithWs2_32.lib
#pragmacomment(lib,"Ws2_32.lib")
#else#include<sys/socket.h>#include<sys/types.h>#include<unistd.h>#endif
int main(void){ //---------------------- //InitializeWinsock. WSADATAwsaData ; intiResult=WSAStartup(MAKEWORD(2,2),&wsaData); if(iResult!=NO_ERROR) { wprintf(L "WSAStartupfailedwitherror:%ld\n",iResult); return 1 ; } //---------------------- //CreateaSOCKETforlisteningfor //incomingconnectionrequests. SOCKETListenSocket ; ListenSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(ListenSocket==INVALID_SOCKET) { wprintf(L "socketfailedwitherror:%ld\n",WSAGetLastError()); WSACleanup(); return 1 ; } //---------------------- //Thesockaddr_instructurespecifiestheaddressfamily, //IPaddress,andportforthesocketthatisbeingbound. sockaddr_inservice ; service.sin_family=AF_INET ; service.sin_addr.s_addr=inet_addr("127.0.0.1"); service.sin_port=htons(27015); if(bind(ListenSocket, (SOCKADDR*)&service,sizeof(service))==SOCKET_ERROR) { wprintf(L"bindfailedwitherror:%ld\n",WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); return 1 ; } //---------------------- //Listenforincomingconnectionrequests. //onthecreatedsocket if(listen(ListenSocket,1)==SOCKET_ERROR) { wprintf(L"listenfailedwitherror:%ld\n",WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); return 1 ; } //---------------------- //CreateaSOCKETforacceptingincomingrequests. SOCKETAcceptSocket ; wprintf(L "Waitingforclienttoconnect...\n"); //---------------------- //Accepttheconnection. AcceptSocket=accept(ListenSocket,NULL,NULL); if(AcceptSocket==INVALID_SOCKET) { wprintf(L "acceptfailedwitherror:%ld\n",WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); return 1 ; } else wprintf(L "Clientconnected.\n"); //Nolongerneedserversocket closesocket(ListenSocket); WSACleanup(); return 0 ;}