Socket Select Fd_isset

Source: Internet
Author: User
Tags function prototype readable socket error
DESCRIPTION the functions Gettimeofday and Settimeofday can and set the time as
As a timezone. The TV argument is a timeval struct, as specified
In <sys/time.h>:

struct Timeval {
time_t tv_sec; * Seconds * *
suseconds_t tv_usec; * Microseconds * *
};

The description of tv_usec is the millisecond portion of the time. In practice, the function and the Timeval returned by the Linux kernel
The time value of the type, tv_usec represents the Microsecond precision (10-6-second square seconds).

The test code is as follows:

#include <stdio.h>
#include <sys/time.h>
#include <time.h>

int gettimeofday (struct timeval *tv, struct timezone);



int main (int argc,char * argv[]) {

struct Timeval TV;
while (1) {
Gettimeofday (&tv,null);
printf ("Time%u:%u\n", tv.tv_sec,tv.tv_usec);
Sleep (2);

}
return 0;

}


The result returned is:

evil@dcenter:~/tmp$./a.out
Time 1,142,077,839:903,605
Time 1,142,077,841:910,129
Time 1,142,077,843:920,155
Time 1,142,077,845:930,180
Time 1,142,077,847:940,205
Time 1,142,077,849:950,231
Time 1,142,077,851:960,256
Time 1,142,077,853:970,280
Time 1,142,077,855:980,307
Time 1,142,077,857:990,331












Linux socket functions are divided into blocking and non-blocking two ways, such as the accept function, in blocking mode, it will always wait for a customer connection. In the case of non-blocking, it is returned immediately. We generally want the program to run in non-blocking mode. One way is to do a dead loop, and constantly query the state of each socket, but this will waste a lot of CPU time. One way to solve this problem is to use the Select function. Use the Select function to communicate with multiple sockets in a non-blocking manner. When a socket needs to be processed, the Select function returns immediately, and the period does not consume CPU time.

Routine Analysis:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define MYPORT 1234//Listening port

#define BACKLOG 5//maximum number of clients to connect

#define BUF_SIZE 200

int Fd_a[backlog]; Connected FD Array
int conn_amount; Number of current connections


void Showclient ()
{
int i;
printf ("Client Amount:%d\n", Conn_amount);
for (i = 0; i < BACKLOG; i++)
{
printf ("[%d]:%d", I, fd_a[i]);
}
printf ("\ n \ nthe");
}

int main (void)
{
int sock_fd, NEW_FD; Listen for SOCK_FD, new connection new_fd
struct sockaddr_in server_addr; Server address Information
struct sockaddr_in client_addr; Connector ' s address information
Socklen_t sin_size;
int yes = 1;
Char Buf[buf_size];
int ret;
int i;


To create a listening socket
if ((SOCK_FD = socket (af_inet, sock_stream, 0)) = = 1)
{
Perror ("Create Listening Socket error!");
Exit (1);
}
Configuring listening sockets
SO_REUSEADDR BOOL allows a nested interface and an address bundle that is already in use.
if (setsockopt (SOCK_FD, Sol_socket, so_reuseaddr, &yes, sizeof (int)) = = 1)
{
Perror ("setsockopt error!");
Exit (1);
}

server_addr.sin_family = af_inet; Host byte order
Server_addr.sin_port = htons (MyPort); Short, network byte
SERVER_ADDR.SIN_ADDR.S_ADDR = Inaddr_any; Automatically fill with my IP
memset (Server_addr.sin_zero, ' the ", sizeof (Server_addr.sin_zero));

Bind the newly created socket to the specified IP and port
if (Bind (SOCK_FD, (struct sockaddr *) &server_addr, sizeof (SERVER_ADDR)) = = 1)
{
Perror ("Bind error!");
Exit (1);
}
Start listening, maximum number of connections is backlog
if (Listen (SOCK_FD, BACKLOG) = = 1)

{
Perror ("Listen error!");
Exit (1);
}

printf ("Listen Port%d\n", MyPort);

Monitor file Descriptor Collection
Fd_set FDSR;
Maximum file number in the Monitor file descriptor collection
int maxsock;
The time returned by the Select timeout.
struct Timeval TV;

Conn_amount = 0;
sin_size = sizeof (CLIENT_ADDR);
Maxsock = SOCK_FD;
while (1)
{
Initializes a collection of file descriptors initialize file descriptor set
Fd_zero (&FDSR);
Add SOCK_FD to the file descriptor collection
fd_set (SOCK_FD, &FDSR);

// timeout set 30 seconds
Tv.tv_sec = 30;
tv.tv_usec = 0;

Add the handle of the active socket to the collection of file descriptors
for (i = 0; i < BACKLOG; i++)
{
if (Fd_a[i]!= 0)
{
Fd_set (Fd_a[i], &FDSR);
}
}
Select function prototype
int Select (Nfds, Readfds, Writefds, Exceptfds, timeout)
Nfds:select the number of file handles monitored, depending on the number of files open in the process, typically set to monitor
the

//maximum file number plus one
Readfds:select monitored collection of readable file handles
Writefds:select A collection of writable file handles that are monitored.
Exceptfds:select a collection of exception file handles that are monitored.
Timeout: Timeout End time for this select.

ret = SELECT (Maxsock + 1, &FDSR, NULL, NULL, &TV);

if (Ret < 0)
{
Perror ("select error!");
Break
}
else if (ret = 0)
{
printf ("timeout\n");
Continue
}

Poll individual file descriptors (sockets)
for (i = 0; i < Conn_amount; i++)
{
Fd_isset (int fd, Fdset *fdset): Check if the fdset associated file handle FD is readable or writable,

The >0 indicates that it is readable and writable.
if (Fd_isset (Fd_a[i], &FDSR))
{
Receive data
ret = recv (Fd_a[i], buf, sizeof (BUF), 0);
if (ret <= 0)//Receive data error
{
printf ("client[%d] close\n", i);
Close (Fd_a[i]);
FD_CLR (Fd_a[i], &FDSR);
Fd_a[i] = 0;
}
else//Data received successfully
{
The last one to receive the data is 0

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.