Select network programming for Linux/Unix IO multiplexing (including source code)

Source: Internet
Author: User
Preface

This section describes how to use basic Linux/Unix functions and select calls to compile a complete server and client example, which can be run on Linux (ubuntu) and Unix (freebsd, the functions of the client and server are as follows:

The client reads a row from the standard input and sends it to the server.

The server reads a row from the network and then outputs the row to the client.

The client receives a response from the server and outputs this line to the standard output.

 

Server

The Code is as follows:

# Include <unistd. h>
# Include <sys/types. h>/* basic system data types */
# Include <sys/socket. h>/* basic socket definitions */
# Include <netinet/in. h>/* sockaddr_in {} and other Internet defns */
# Include <arpa/inet. h>/* inet (3) functions */
# Include <sys/select. h>/* select function */

# Include <stdlib. h>
# Include <errno. h>
# Include <stdio. h>
# Include <string. h>

# Define MAXLINE 10240

Void handle (int * clientSockFds, int maxFds, fd_set * pRset, fd_set * pAllset );

Int main (int argc, char ** argv)
{
Int servPort = 6888;
Int listenq = 1024;

Int listenfd, connfd;
Struct sockaddr_in cliaddr, servaddr;
Socklen_t socklen = sizeof (struct sockaddr_in );
Int nready, nread;
Char buf [MAXLINE];
Int clientSockFds [FD_SETSIZE];
Fd_set allset, rset;
Int maxfd;

Listenfd = socket (AF_INET, SOCK_STREAM, 0 );
If (listenfd <0 ){
Perror ("socket error ");
Return-1;
}

Int opt = 1;
If (setsockopt (listenfd, SOL_SOCKET, SO_REUSEADDR, & opt, sizeof (opt) <0 ){
Perror ("setsockopt error ");
}

Bzero (& servaddr, sizeof (servaddr ));
Servaddr. sin_family = AF_INET;
Servaddr. sin_addr.s_addr = htonl (INADDR_ANY );
Servaddr. sin_port = htons (servPort );


If (bind (listenfd, (struct sockaddr *) & servaddr, socklen) =-1 ){
Perror ("bind error ");
Exit (-1 );
}

If (listen (listenfd, listenq) <0 ){
Perror ("listen error ");
Return-1;
}

Int I = 0;
For (I = 0; I <FD_SETSIZE; I ++)
ClientSockFds [I] =-1;
FD_ZERO (& allset );
FD_SET (listenfd, & allset );
Maxfd = listenfd;

Printf ("echo server use select startup, listen on port % d \ n", servPort );
Printf ("max connection: % d \ n", FD_SETSIZE );

For (;;){
Rset = allset;
Nready = select (maxfd + 1, & rset, NULL );
If (nready <0 ){
Perror ("select error ");
Continue;
}
If (FD_ISSET (listenfd, & rset )){
Connfd = accept (listenfd, (struct sockaddr *) & cliaddr, & socklen );
If (connfd <0 ){
Perror ("accept error ");
Continue;
}

Sprintf (buf, "accept form % s: % d \ n", inet_ntoa (cliaddr. sin_addr), cliaddr. sin_port );
Printf (buf ,"");

For (I = 0; I <FD_SETSIZE; I ++ ){
If (clientSockFds [I] =-1 ){
ClientSockFds [I] = connfd;
Break;
}
}
If (I = FD_SETSIZE ){
Fprintf (stderr, "too multicast connection, more than % d \ n", FD_SETSIZE );
Close (connfd );
Continue;
}
If (connfd> maxfd)
Maxfd = connfd;

FD_SET (connfd, & allset );
If (-- nready <= 0)
Continue;
}

Handle (clientSockFds, maxfd, & rset, & allset );
}
}


Void handle (int * clientSockFds, int maxFds, fd_set * pRset, fd_set * pAllset ){
Int nread;
Int I;
Char buf [MAXLINE];
For (I = 0; I <maxFds; I ++ ){
If (clientSockFds [I]! =-1 ){
If (FD_ISSET (clientSockFds [I], pRset )){
Nread = read (clientSockFds [I], buf, MAXLINE); // read the client socket stream
If (nread <0 ){
Perror ("read error ");
Close (clientSockFds [I]);
FD_CLR (clientSockFds [I], pAllset );
ClientSockFds [I] =-1;
Continue;
}
If (nread = 0 ){
Printf ("client close the connection \ n ");
Close (clientSockFds [I]);
FD_CLR (clientSockFds [I], pAllset );
ClientSockFds [I] =-1;
Continue;
}

Write (clientSockFds [I], buf, nread); // The response client may fail and will not be processed at the moment
}
}
}

}

 

Client

The Code is as follows:

# Include <unistd. h>
# Include <sys/types. h>/* basic system data types */
# Include <sys/socket. h>/* basic socket definitions */
# Include <netinet/in. h>/* sockaddr_in {} and other Internet defns */
# Include <arpa/inet. h>/* inet (3) functions */
# Include <sys/select. h>/* select function */

# Include <stdlib. h>
# Include <errno. h>
# Include <stdio. h>
# Include <string. h>

# Define MAXLINE 10240
# Define max (a, B) (a)> (B )? (A): (B ))
// Typedef struct sockaddr SA;

Void handle (int sockfd );

Int main (int argc, char ** argv)
{
Char * servInetAddr = "127.0.0.1 ";
Int servPort = 6888;
Char buf [MAXLINE];
Int connfd;
Struct sockaddr_in servaddr;

If (argc = 2 ){
ServInetAddr = argv [1];
}
If (argc = 3 ){
ServInetAddr = argv [1];
ServPort = atoi (argv [2]);
}
If (argc> 3 ){
Printf ("usage: selectechoclient <IPaddress> <Port> \ n ");
Return-1;
}

Connfd = socket (AF_INET, SOCK_STREAM, 0 );

Bzero (& servaddr, sizeof (servaddr ));
Servaddr. sin_family = AF_INET;
Servaddr. sin_port = htons (servPort );
Inet_ton (AF_INET, servInetAddr, & servaddr. sin_addr );

If (connect (connfd, (struct sockaddr *) & servaddr, sizeof (servaddr) <0 ){
Perror ("connect error ");
Return-1;
}
Printf ("welcome to selectechoclient \ n ");
Handle (connfd);/* do it all */
Close (connfd );
Printf ("exit \ n ");
Exit (0 );
}


Void handle (int connfd)
{
FILE * fp = stdin;
Char sendline [MAXLINE], recvline [MAXLINE];
Fd_set rset;
FD_ZERO (& rset );
Int maxfds = max (fileno (fp), connfd) + 1;
Int nread;
For (;;){
FD_SET (fileno (fp), & rset );
FD_SET (connfd, & rset );

If (select (maxfds, & rset, NULL, NULL) =-1 ){
Perror ("select error ");
Continue;
}

If (FD_ISSET (connfd, & rset )){
// Receives the Server Response
Nread = read (connfd, recvline, MAXLINE );
If (nread = 0 ){
Printf ("server close the connection \ n ");
Break;
}
Else if (nread =-1 ){
Perror ("read error ");
Break;
}
Else {
// Server response
Write (STDOUT_FILENO, recvline, nread );
}
}

If (FD_ISSET (fileno (fp), & rset )){
// The standard input is readable.
If (fgets (sendline, MAXLINE, fp) = NULL ){
// Eof exit
Break;
}
Else {
Write (connfd, sendline, strlen (sendline ));
}
}

}
}

 

Download and compile

Compile and start the server

gcc selectechoserver.c -o selectechoserver

Compile and start the client

gcc selectechoclient.c -o selectechoclient

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.