select监听多个client -- linux函数
使用select函数能够以非堵塞的方式和多个socket通信。程序仅仅是演示select函数的使用,功能很easy,即使某个连接关闭以后也不会改动当前连接数。连接数达到最大值后会终止程序。
1. 程序使用了一个数组fd_A,通信開始后把须要通信的多个socket描写叙述符都放入此数组。
2. 首先生成一个叫sock_fd的socket描写叙述符,用于监听port。
3. 将sock_fd和数组fd_A中不为0的描写叙述符放入select将检查的集合fdsr。
4. 处理fdsr中能够接收数据的连接。假设是sock_fd,表明有新连接增加。将新增加连接的socket描写叙述符放置到fd_A。
这部分代码实现逻辑不错,只是有点bug,对套接字缓存未做处理完整。
#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); }
我这里做改动(大概逻辑)
for(i=0;i<BACKLOG;i++)
{
tcpSockIndex[i] = -1;
} while(1)
{
FD_ZERO(&readfds);
FD_SET(tcpSock, &readfds); maxfdp = maxfdp>tcpSock?maxfdp:tcpSock; for(i=0;i<BACKLOG;i++)
{
// AB_LOG("FD_SET tcpSockIndex[%d] = %d.\n", i, tcpSockIndex[i]);
if(-1 != tcpSockIndex[i])
{
FD_SET(tcpSockIndex[i], &readfds);
maxfdp = maxfdp>tcpSockIndex[i]? maxfdp:tcpSockIndex[i];
}
} timeout.tv_sec = SELECT_TIME_OUT_TM;
timeout.tv_usec = 0; ret = select(maxfdp+1, &readfds, NULL, NULL, &timeout);
if(ret < 0)
{
AB_PERROR("select error!\n");
return ;
}
else if(0 == ret)
{
AB_PERROR("select time out!\n");
} //处理client发送的报文
for(i=0; i<BACKLOG; i++)
{
if ( -1 != tcpSockIndex[i] &&
FD_ISSET(tcpSockIndex[i], &readfds))
{
AB_LOG("--- tcp client ---.\n");
pthread_t pthd2;
TCP_SOCK_T * pTcpSock = NULL;
pTcpSock = (TCP_SOCK_T *)malloc(sizeof(TCP_SOCK_T));
pTcpSock->sock = tcpSockIndex[i];
pthread_create(&pthd2, NULL, bc_sock_handle_client_data, (void *)pTcpSock); #if 0
bc_sock_handle_client_data(tcpSockIndex[i]);
ret = read(tcpSockIndex[i], NULL, 0);
AB_LOG("close tcpSockIndex[%d] = %d, ret = %d.\n", i, tcpSockIndex[i], ret ); //关闭client连接的套接字
if(-1 == tcpSockIndex[i]) close(tcpSockIndex[i]);
#endif //清空client字符集
FD_CLR(tcpSockIndex[i], &readfds);
tcpSockIndex[i] = -1;
tcpClientConnNum --;
}
} //获取client连接过来的套接字
if(FD_ISSET(tcpSock, &readfds))
{
AB_LOG("--- tcp server ---.\n");
if((tcpSockClient = accept(tcpSock,
(struct sockaddr*)&chiAddr, &cliLen)) <= 0 )
{
AB_PERROR("BCHV accept socket error: %s(errno: %d).\n",strerror(errno), errno);
continue;
} //在套接字数组中找出一个可用加入的位置。 for(i=0,tcpSockFlag=0; i<BACKLOG; i++)
{
AB_LOG("tcpSockIndex[%d] = %d.\n", i, tcpSockIndex[i]);
if(-1 == tcpSockIndex[i])
{
tcpSockIndex[i] = tcpSockClient;
tcpClientConnNum ++;
AB_LOG("new connection client[%d] %08X:%d.\n", tcpClientConnNum,
chiAddr.sin_addr.s_addr, ntohs(chiAddr.sin_port));
//错误打印
//AB_LOG("new connection client[%d] %s.\n", tcpClientConnNum,
// inet_ntoa(chiAddr.sin_addr));
#if 0
if (sock_c > maxfdp)
maxfdp = sock_c;
#endif
tcpSockFlag = 1;
break;
}
}
//超过最大连接请求。能够发送client断开连接
if(0 == tcpSockFlag)
{
AB_LOG("max connections arrive, exit\n");
send(tcpSockClient, "bye", 4, 0);
close(tcpSockClient);
}
}
} //关闭全部client套接字
for(i=0; i<BACKLOG; i++)
{
if(-1 != tcpSockIndex[i])
{
close(tcpSockIndex[i]);
}
}
文章摘自 http://www.cnblogs.com/faraway/archive/2009/03/06/1404449.html
select监听多个client -- linux函数的更多相关文章
- select监听服务端
# can_read, can_write, _ = select.select(inputs, outputs, None, None)## 第一个参数是我们需要监听可读的套接字, 第二个参数是我们 ...
- Hi3559AV100板载开发系列-pthread_create()下V4L2接口MJPEG像素格式的VIDIOC_DQBUF error问题解决-采用阻塞方式下select监听
最近一直加班加点进行基于Hi3559AV100平台的BOXER-8410AI板载开发,在开发的过程中,遇到了相当多的问题,其一是板载的开发资料没有且功能不完整,厂家不提供太多售后技术支持,厂家对部分 ...
- 多个进程对同一个监听套接字调用函数gen_tcp:accept/1
源于<<erlang程序设计>>的第14章的14.1.4大约第197页. 未发现多个进程对同一个监听套接字调用函数gen_tcp:accept/1比单进程的效率更高或者更快.
- select监听udp消息
服务端 #!/usr/bin/python2.6 # -*- coding:utf-8 -*- import json import socket import select def socketse ...
- layui的select监听
首先,select一定要放在<form class="layui-form" ></form>里面 然后,加监听<select id="id ...
- Js事件监听封装(支持匿名函数)
先看demo:http://liutian1937.github.io/demo/EventListen.html/*绑定事件与取消绑定*/ var handleHash = {}; var bind ...
- 实时监听 mysql 操作,Linux 版
效果 场景:某数据库新增了某条记录,服务器可以监听到变化的数据与操作,如 增加一条记录: id = 1009,name=''test,number = 11 服务器监听结果: 实现过程 测试过程:数据 ...
- PostgreSQL服务端监听设置及client连接方法
背景介绍: PostgreSQL服务端执行在RedHat Linux上,IP为:192.168.230.128 client安装在Windows XP上, IP为:192.168.230.1 配置方法 ...
- linux epoll机制对TCP 客户端和服务端的监听C代码通用框架实现
1 TCP简介 tcp是一种基于流的应用层协议,其“可靠的数据传输”实现的原理就是,“拥塞控制”的滑动窗口机制,该机制包含的算法主要有“慢启动”,“拥塞避免”,“快速重传”. 2 TCP socket ...
随机推荐
- 不同狀況下的 bq25896 register
no charger時的 bq25896 register [bq25890 reg@] [0x0]=0x7f [0x1]=0x6 [0x2]=0x91 [0x3]=0x1a [0x4]=0x8 [0 ...
- uniSWF使用注意事项
美术方面,也就是使用FLASH这里的用户,请注意以下几点, 1.把相同的图案做成元件: 2.凡是补间产生的动画物体,也要做成元件: 以上便可以节省大量的空间,因为当迩把图案做成元件的话,UNISWF导 ...
- php自动获取字符串编码函数mb_detect_encoding
当在php中使用mb_detect_encoding函数进行编码识别时,很多人都碰到过识别编码有误的问题,例如对与GB2312和UTF- 8,或者UTF-8和GBK(这里主要是对于cp936的判断), ...
- Adoquery的 moveby和GotoBookmark,RecNo
GotoBookmark 是必须存在的记录,再次返回原来那个记录的位置,但是原来的那个记录必须存在,所以不适合[删除订单后回到原来的位置],因为原来的订单已经不存在了,删除了, moveby(),从当 ...
- cmake ccmake
下载libqrencode源码编译过程 git clone https://github.com/fukuchi/libqrencode.git 2001 mkdir build 2002 cd ...
- 关于 Bellman-Ford 与 Floyd 算法的一点感想
在四种常用的最短路算法 Dijkstra, SPFA, floyd, Bellman-Ford 中, Dijks 和 SPFA 的使用较为普遍, 对大多数人来说, 也较为熟悉. 然而, floyd 与 ...
- Class definition
Prerequisite Articles (None) Related Articles Category Accessor method A class definition is the spe ...
- 【postman】postman测试API报错如下:TypeError: Failed to execute 'fetch' on 'Window': Invalid value 对中文支持不好
使用postman测试APi的时候,因为系统需要在header部带上登录用户的信息,所以 如下: 然后测试报错如下:TypeError: Failed to execute 'fetch' on 'W ...
- 无插件,跨平台,基于WebGL的三维地球来了!!!
用户通过浏览器即可递交数据到同一个地理信息系统中,操作简单,跨平台 ,无插件,可扩展,高效共享 ,完美匹配超大数据量发布! 近年来,随着计算机图形学.虚拟现实.卫星遥感.航空摄影.激光雷达等技术的迅猛 ...
- xshell登陆腾讯云服务器
2016-12-11 00:17:36 前段时间在同学的介绍下关注了一下腾讯云:然后里面有学生优惠可以拿到免费的域名和云服务器.所以感兴趣就实验了一下,今天中午抢到了“1元特惠的学生包”,里面有免 ...