linux网络编程 | c | select实现多路IO转接服务器

poll实现多路IO转接服务器

基于该视频完成

04-poll函数实现服务器_哔哩哔哩_bilibili

通过响应式--多路IO转接实现

要求:能看懂看,看不懂也没啥大事,现在基本都用epoll代替了

大家看视频思路吧,代码就是从讲义里面copy了一份,因为不是很重要的东西

文章目录

思路

代码实现

warp.h

c 复制代码
#ifndef __WRAP_H_
#define __WRAP_H_
#include<sys/epoll.h>
//#include<event2/event.h>
#include<sys/select.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<errno.h>
#include<string.h>
#include<dirent.h>
#include<sys/stat.h>
#include<wait.h>
#include<sys/mman.h>
#include<signal.h>
#include<pthread.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<ctype.h>
#include<strings.h>
#include<netinet/ip.h>
#define SRV_PORT 1234


void perr_exit(const char *s);
int Accept(int fd,struct sockaddr *sa,socklen_t * salenptr);
int Bind(int fd, const struct sockaddr *sa, socklen_t salen);
int Connect(int fd, const struct sockaddr *sa, socklen_t addrlen);
int Listen(int fd, int backlog);
int Socket(int family, int type, int protocol);
size_t Read(int fd, void *ptr, size_t nbytes);
ssize_t Write(int fd,const void *ptr,size_t nbytes);
int Close(int fd);
ssize_t Readn(int fd, void *vptr, size_t n);
ssize_t Writen(int fd, const void *vptr, size_t n);
ssize_t my_read(int fd, char  *ptr);
ssize_t Readline(int fd, void *vptr, size_t maxlen);



#endif

warp.c

c 复制代码
#include"warp.h"


void perr_exit(const char *s)
{
	perror(s);
	exit(1);
}

int Accept(int fd,struct sockaddr *sa,socklen_t * salenptr)
{
	int n;
again:
	if((n=accept(fd,sa,salenptr))<0)
	{
		if((errno==ECONNABORTED)||(errno==EINTR))
			goto again;
		else
			perr_exit("accept error");
	}
	return n;
}

int Bind(int fd, const struct sockaddr *sa, socklen_t salen)
{
	int n;
	if((n=bind(fd,sa,salen))<0)
		perr_exit("bind error");

	return n;
}

int Connect(int fd, const struct sockaddr *sa, socklen_t addrlen)
{
	int n;
	n=connect(fd,sa,addrlen);
	if(n<0)
	{
		perr_exit("connect error");
	}
	return n;
}

int Listen(int fd, int backlog)
{
	int n;
	if((n=listen(fd,backlog))<0)
		perr_exit("listen error");
	return n;
}

int Socket(int family, int type, int protocol)
{
	int n;
	if((n=socket(family,type,protocol))<0)
		perr_exit("socket error");
	return n;
}

size_t Read(int fd, void *ptr, size_t nbytes)
{
	ssize_t n;
again:
	if((n=read(fd,ptr,nbytes))==-1)
	{
		if(errno==EINTR)
			goto again;
		else
			return -1;
	}
	return n;
}

ssize_t Write(int fd,const void *ptr,size_t nbytes)
{
	ssize_t n;
again:
	if((n=write(fd,ptr,nbytes))==-1)
	{
		if(errno==EINTR)
			goto again;
		else
			return -1;
	}

	return 0;
}

int Close(int fd)
{
	int n;
	if((n=close(fd))==-1)
		perr_exit("close error");

	return n;
}

ssize_t Readn(int fd, void *vptr, size_t n)
{
	size_t nleft;
	ssize_t nread;
	char *ptr;

	ptr=vptr;
	nleft=n;

	while(nleft>0)
	{
		if((nread=read(fd,ptr,nleft))<0)
		{
			if(errno==EINTR)
				nread=0;
			else
				return -1;
		}
		else if(nread==0)
			break;
	
	}
}
ssize_t Writen(int fd, const void *vptr, size_t n)
{
	size_t nleft;
	ssize_t nwritten;
	char *ptr;

	ptr=(char *)vptr;
	nleft=n;

	while(nleft>0)
	{
		if((nwritten=write(fd,ptr,nleft))<=0)
		{
			if(nwritten<0&&errno==EINTR)
				nwritten=0;
			else
				return -1;
		}
		nleft-=nwritten;
		ptr+=nwritten;
	}
	return n;
}

ssize_t my_read(int fd, char  *ptr)
{
	static int read_cnt;
	static char *read_ptr;
	static char read_buf[100];

	if(read_cnt<=0)
	{
again:
		if((read_cnt=read(fd,read_buf,sizeof(read_buf)))<0)
		{
			if(errno==EINTR)
				goto again;
			return -1;
		}else if(read_cnt==0)
			return 0;
		read_ptr=read_buf;
	}
	read_cnt--;
	*ptr=*read_ptr++;
	return 1;
}

ssize_t Readline(int fd, void *vptr, size_t maxlen)
{
	ssize_t n,rc;
	char c,*ptr;
	ptr=vptr;

	for(n=1;n<maxlen;n++)
	{
		if((rc=my_read(fd,&c))==1)
		{
			*ptr++=c;
			if(c=='\n')
				break;
		}else if(rc==0)
		{
			*ptr=0;
			return n-1;
		}
		else	
			return -1;
	}
	*ptr=0;
	return n;
}

multi_poll_sever.c

c 复制代码
1./* server.c */  
2.#include <stdio.h>  
3.#include <stdlib.h>  
4.#include <string.h>  
5.#include <netinet/in.h>  
6.#include <arpa/inet.h>  
7.#include <poll.h>  
8.#include <errno.h>  
9.#include "wrap.h"  
10.  
11.#define MAXLINE 80  
12.#define SERV_PORT 6666  
13.#define OPEN_MAX 1024  
14.  
15.int main(int argc, char *argv[])  
16.{  
17.    int i, j, maxi, listenfd, connfd, sockfd;  
18.    int nready;  
19.    ssize_t n;  
20.    char buf[MAXLINE], str[INET_ADDRSTRLEN];  
21.    socklen_t clilen;  
22.    struct pollfd client[OPEN_MAX];  
23.    struct sockaddr_in cliaddr, servaddr;  
24.  
25.    listenfd = Socket(AF_INET, SOCK_STREAM, 0);  
26.  
27.    bzero(&servaddr, sizeof(servaddr));  
28.    servaddr.sin_family = AF_INET;  
29.    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);  
30.    servaddr.sin_port = htons(SERV_PORT);  
31.  
32.    Bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));  
33.  
34.    Listen(listenfd, 20);  
35.  
36.    client[0].fd = listenfd;  
37.    client[0].events = POLLRDNORM;                  /* listenfd监听普通读事件 */  
38.  
39.    for (i = 1; i < OPEN_MAX; i++)  
40.        client[i].fd = -1;                          /* 用-1初始化client[]里剩下元素 */  
41.    maxi = 0;                                       /* client[]数组有效元素中最大元素下标 */  
42.  
43.    for ( ; ; ) {  
44.        nready = poll(client, maxi+1, -1);          /* 阻塞 */  
45.        if (client[0].revents & POLLRDNORM) {       /* 有客户端链接请求 */  
46.            clilen = sizeof(cliaddr);  
47.            connfd = Accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);  
48.            printf("received from %s at PORT %d\n",  
49.                    inet_ntop(AF_INET, &cliaddr.sin_addr, str, sizeof(str)),  
50.                    ntohs(cliaddr.sin_port));  
51.            for (i = 1; i < OPEN_MAX; i++) {  
52.                if (client[i].fd < 0) {  
53.                    client[i].fd = connfd;  /* 找到client[]中空闲的位置,存放accept返回的connfd */  
54.                    break;  
55.                }  
56.            }  
57.  
58.            if (i == OPEN_MAX)  
59.                perr_exit("too many clients");  
60.  
61.            client[i].events = POLLRDNORM;      /* 设置刚刚返回的connfd,监控读事件 */  
62.            if (i > maxi)  
63.                maxi = i;                       /* 更新client[]中最大元素下标 */  
64.            if (--nready <= 0)  
65.                continue;                       /* 没有更多就绪事件时,继续回到poll阻塞 */  
66.        }  
67.        for (i = 1; i <= maxi; i++) {            /* 检测client[] */  
68.            if ((sockfd = client[i].fd) < 0)  
69.                continue;  
70.            if (client[i].revents & (POLLRDNORM | POLLERR)) {  
71.                if ((n = Read(sockfd, buf, MAXLINE)) < 0) {  
72.                    if (errno == ECONNRESET) { /* 当收到 RST标志时 */  
73.                        /* connection reset by client */  
74.                        printf("client[%d] aborted connection\n", i);  
75.                        Close(sockfd);  
76.                        client[i].fd = -1;  
77.                    } else {  
78.                        perr_exit("read error");  
79.                    }  
80.                } else if (n == 0) {  
81.                    /* connection closed by client */  
82.                    printf("client[%d] closed connection\n", i);  
83.                    Close(sockfd);  
84.                    client[i].fd = -1;  
85.                } else {  
86.                    for (j = 0; j < n; j++)  
87.                        buf[j] = toupper(buf[j]);  
88.                        Writen(sockfd, buf, n);  
89.                }  
90.                if (--nready <= 0)  
91.                    break;              /* no more readable descriptors */  
92.            }  
93.        }  
94.    }  
95.    return 0;  
96.}  
相关推荐
滴水之功1 小时前
VMware ubuntu16.04怎么设置静态IP联网
linux·ubuntu
mit6.8241 小时前
[Pro Git#3] 远程仓库 | ssh key | .gitignore配置
linux·git·ubuntu
air_7291 小时前
抓包分析DHCP的工作过程
linux·运维·服务器·网络·华为·dhcp
学Linux的语莫1 小时前
负载均衡,高可用,监控服务搭建总结
linux·服务器·分布式·ceph·lvs
小技与小术1 小时前
docker搭建haproxy实现负载均衡
linux·运维·docker·容器·负载均衡
岳轩子1 小时前
Http协议在网站中的体现
网络·网络协议·http·tomcat
唐可盐1 小时前
解决Centos7系统更新时报错:Could not resolve host: mirrorlist.centos.org; 未知的错误
linux·运维·centos
什么半岛铁盒2 小时前
Linux常用指令-----下
linux·服务器·数据库
killer-p2 小时前
ARM Linux 虚拟环境搭建
linux·arm开发
Java小白笔记2 小时前
Web项目图片视频加载缓慢/首屏加载白屏
linux·服务器·音视频