需要开启两个及以上的客户端进行运行,服务器端实现数据转发的功能
server端
#include<stdio.h>
#include<sys/epoll.h>
#include<unistd.h>
#include<sys/socket.h>
#include<errno.h>
#include<stdlib.h>
#include<ctype.h>
#include<arpa/inet.h>
#include<strings.h>
#include<sys/select.h>
#include<string.h>
#include<fcntl.h>
#define SERV_PORT 6666
#define SERV_IP "127.0.0.1"
#define MAXLINE 8192
#define OPEN_MAX 1024
struct Node//记录已连上的客户端
{
int fd;
struct Node *next;
};
typedef struct Node Node;
struct Node *head = NULL;
struct Node *end = NULL;
/*
将客户端文件描述符插入到链表中
*/
void add( int fd)
{
if(end == NULL)
{
end = (struct Node *)malloc(sizeof(Node));
end->fd = fd;
head = end;
end->next=NULL;
}
else//尾插法
{
end->next = (struct Node*)malloc(sizeof(Node));
end->next->fd = fd;
end = end->next;
end->next=NULL;
}
}
/*
将客户端描述符从链表中删除
*/
int move(int fd)
{
struct Node *p = head;
struct Node *q = p;
while(p != NULL)
{
if(p->fd == fd)
{
close(p->fd);
q->next = p->next;
free(p);
break;
}
q = p;
p = p->next;
}
return -1;
}
/*
将新的客户端添加到epfd
*/
void addfd(int epollfd, int fd, int flag)
{
struct epoll_event tep;
tep.data.fd = fd;
tep.events = EPOLLIN;
if(flag == 1)
tep.events = EPOLLIN | EPOLLET;//边缘触发
epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &tep);
int ret = fcntl(fd, F_SETFL, fcntl(fd, F_GETFD, 0) | O_NONBLOCK);//设置为非阻塞
if(ret == -1)
{
perror("fcntl err")