使用select函数可以以非阻塞的方式和多个socket通信。程序只是演示select函数的使用,功能非常简单,即使某个连接关闭以后也不会修改当前连接数,连接数达到最大值后会终止程序。

1. 程序使用了一个数组fd_A,通信开始后把需要通信的多个socket描述符都放入此数组。

2. 首先生成一个叫sock_fd的socket描述符,用于监听端口。

3. 将sock_fd和数组fd_A中不为0的描述符放入select将检查的集合fdsr。

4. 处理fdsr中可以接收数据的连接。如果是sock_fd,表明有新连接加入,将新加入连接的socket描述符放置到fd_A。

#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    // the port users will be connecting to

#define BACKLOG 5     // how many pending connections queue will hold

#define BUF_SIZE 200

int fd_A[BACKLOG];    // accepted connection fd

int conn_amount;    // current connection amount

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\n");

}

int main(void)

{

int sock_fd, new_fd;  // listen on sock_fd, new connection on 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;

if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {

perror("socket");

exit(1);

}

if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {

perror("setsockopt");

exit(1);

}

server_addr.sin_family = AF_INET;         // host byte order

server_addr.sin_port = htons(MYPORT);     // short, network byte order

server_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP

memset(server_addr.sin_zero, '\0', sizeof(server_addr.sin_zero));

if (bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {

perror("bind");

exit(1);

}

if (listen(sock_fd, BACKLOG) == -1) {

perror("listen");

exit(1);

}

printf("listen port %d\n", MYPORT);

fd_set fdsr;

int maxsock;

struct timeval tv;

conn_amount = 0;

sin_size = sizeof(client_addr);

maxsock = sock_fd;

while (1) {

// initialize file descriptor set

FD_ZERO(&fdsr);

FD_SET(sock_fd, &fdsr);

// timeout setting

tv.tv_sec = 30;

tv.tv_usec = 0;

// add active connection to fd set

for (i = 0; i < BACKLOG; i++) {

if (fd_A[i] != 0) {

FD_SET(fd_A[i], &fdsr);

}

}

ret = select(maxsock + 1, &fdsr, NULL, NULL, &tv);

if (ret < 0) {

perror("select");

break;

} else if (ret == 0) {

printf("timeout\n");

continue;

}

// check every fd in the set

for (i = 0; i < conn_amount; i++) {

if (FD_ISSET(fd_A[i], &fdsr)) {

ret = recv(fd_A[i], buf, sizeof(buf), 0);

if (ret <= 0) {        // client close

printf("client[%d] close\n", i);

close(fd_A[i]);

FD_CLR(fd_A[i], &fdsr);

fd_A[i] = 0;

} else {        // receive data

if (ret < BUF_SIZE)

memset(&buf[ret], '\0', 1);

printf("client[%d] send:%s\n", i, buf);

}

}

}

// check whether a new connection comes

if (FD_ISSET(sock_fd, &fdsr)) {

new_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size);

if (new_fd <= 0) {

perror("accept");

continue;

}

// add to fd queue

if (conn_amount < BACKLOG) {

fd_A[conn_amount++] = new_fd;

printf("new connection client[%d] %s:%d\n", conn_amount,

inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

if (new_fd > maxsock)

maxsock = new_fd;

}

else {

printf("max connections arrive, exit\n");

send(new_fd, "bye", 4, 0);

close(new_fd);

break;

}

}

showclient();

}

// close other connections

for (i = 0; i < BACKLOG; i++) {

if (fd_A[i] != 0) {

close(fd_A[i]);

}

}

exit(0);

}

转 linux socket的select函数例子的更多相关文章

  1. linux c语言 select函数用法

    linux c语言 select函数用法 表头文件 #i nclude<sys/time.h> #i nclude<sys/types.h> #i nclude<unis ...

  2. linux c语言 select函数使用方法

    linux c语言 select函数使用方法 表头文件 #i nclude<sys/time.h> #i nclude<sys/types.h> #i nclude<un ...

  3. linux 下的select函数

    函数原型 /* According to POSIX.1-2001 */ #include <sys/select.h>  //头文件 /* According to earlier st ...

  4. linux select函数:Linux下select函数的使用详解【转】

    本文转载自;http://www.bkjia.com/article/28216.html Linux下select函数的使用 Linux下select函数的使用 一.Select 函数详细介绍 Se ...

  5. linux c中select使用方法

    1.select函数作为定时器使用    it_value.tv_sec = 0;    it_value.tv_usec = 100000:    select(1,NULL,NULL,NULL,& ...

  6. select()函数用法二

    Select在Socket编程中还是比较重要的,可是对于初学Socket的人来说都不太爱用Select写程序,他们只是习惯写诸如 connect.accept.recv或recvfrom这样的阻塞程序 ...

  7. linux c中select使用技巧

    1.select函数作为定时器使用    it_value.tv_sec = 0;    it_value.tv_usec = 100000:    select(1,NULL,NULL,NULL,& ...

  8. Linux下select函数的使用

    一.Select 函数详细介绍 Select在Socket编程中还是比较重要的,可是对于初学Socket的人来说都不太爱用Select写程序,他们只是习惯写诸如connect. accept.recv ...

  9. linux select函数详解

    linux select函数详解 在Linux中,我们可以使用select函数实现I/O端口的复用,传递给 select函数的参数会告诉内核: •我们所关心的文件描述符 •对每个描述符,我们所关心的状 ...

随机推荐

  1. Image Is Everything LA2995

    白书第一章例题6 构造.思维.几何. 分别从几个角度去看,有矛盾就删掉,最后遍历一下统计个数 方法证明:第一个方块肯定要删除.假设前k个必须删除,第k+1个矛盾出现,假如不删掉,矛盾将持续存在,故必须 ...

  2. uva1609 Foul Play

    思维 创造条件使一轮比赛之后仍满足1号打败至少一半,并剩下至少一个t' 紫书上的思路很清晰阶段1,3保证黑色至少消灭1半 #include<cstdio> #include<vect ...

  3. index 定义 v-for 未使用变量 实际是没有 :key="index"

    需要有 :key="index" <Checkbox :label="item.key" :key="index" v-for=&qu ...

  4. 1.1 Qt入门

    学习Qt的前提是学好C++. 我刚入门Qt,打算趁着暑假2个月时间来学习<C++ GUI Qt 4>这本书. 现在有Qt4和Qt5,似乎很多公司都还是在使用Qt4,所以我也就选择了学习Qt ...

  5. 2019天梯赛练习题(L2专项练习)

    7-2 列出连通集 (25 分) 给定一个有N个顶点和E条边的无向图,请用DFS和BFS分别列出其所有的连通集.假设顶点从0到N−1编号.进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序 ...

  6. hdu5279 YJC plays Minecraft

    题目描述 题解: 岛屿之间的边砍/不砍情况有$2^n$种, 但是需要剪掉所有的岛上都首尾相连的情况. $dp$一下对于完全图没有限制($f$)/有限制($g$)的情况数. 方程:$$f[i]=\sum ...

  7. 提高CPU使用率

    某些特殊时候,需要提升下cpu的利用率,此时……………………需要一个极其简单的脚本来完成! #!/bin/bash while (true);do { for i in $(seq 100000 10 ...

  8. 页面布局排版-block,inline,float,relative,absolute等

    1.span和div的区别 div是块元素(block),span是行内元素(inline): span什么事也不会做,它存在的目的在与为开发者给它所围绕的元素指定样式.div类似,不过它引入了行分隔 ...

  9. PROPAGATION_REQUIRED,ISOLATION_DEFAULT; '',-java.lang.Exception

    转https://stackoverflow.com/questions/29117679/spring-transactional-management-propagation-required-i ...

  10. 【HIHOCODER 1605】小Hi的生成树计数

    描述 小Hi最近对生成树(包含所有顶点的联通无环子图.)非常的感兴趣,他想知道对于特定的简单平面无向图是不是存在求生成树个数的简单方法. 小Hi定义了这样的图:一个以{0,1,2--n}为顶点的图,顶 ...