|
int listen(int s, int backlogLength) |
|
int accept ( int s, struct sockaddr *cli_addr, socklen_t *addrlen) |
|
int s_listen; // The listen socket int s_data; // The data socket struct sockaddr_in in_addr; // Help structures to form netw address struct sockaddr_in client; int length; /* --------------------------------------- Create the TCP listen socket --------------------------------------- */ s_listen = socket( AF_INET, SOCK_STREAM, 0 ); // Create a TCP socket /* ------------------------------------------------------ Bind the socket to a network address This makes the socket identifiable by (IPaddr, Port#) ------------------------------------------------------ */ in_addr.sin_family = AF_INET; in_addr.sin_addr.s_addr = htonl(INADDR_ANY); in_addr.sin_port = htons(SrvPortNumber); if ( bind(s_listen, (struct sockaddr *)&in_addr, // Bind socket to (IP-addr, Port#) sizeof(in_addr)) == 0 ) { perror("Bind: "); exit(1); } /* --------------------------------------------------------- Enable socket s_listen to accept connect requests --------------------------------------------------------- */ listen(s_listen, 5); // Change socket to a "listen" socket /* --------------------------------------------------------- Accept TCP connection calls --------------------------------------------------------- */ while ( 1 ) { length = sizeof(struct sockaddr_in); /* ======================================================= Server program waits for client's connection requests ======================================================= */ s_data = accept( s_listen, &client, &length); // s_data = data socket // The accept( ) function will a // data socket of the TCP connection // establish with the client program /* =========================================== Now you can send and receive data using the s_data socket =========================================== */ read ( s_data, ....) to receive client's requests write( s_data, ....) to send data to client close( s_data) to disconnect } |