#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#define ERR_MSG(msg) \
do \
{ \
fprintf(stderr, "line:%d ", __LINE__); \
perror(msg); \
} while (0)
#define IP "192.168.250.100" // 本机IP ifconfig
#define PORT 8888 // 1024-49151
int main(int argc, char const *argv[])
{
char buf[128] = {0};
int fd1, fd2;
int ret, i,res;
struct epoll_event event;
struct epoll_event events[10];
// 创建套接字
int newsfd;
int sfd = socket(AF_INET, SOCK_STREAM, 0);
if (sfd < 0)
{
ERR_MSG("socket");
return -1;
}
printf("sfd = %d\n", sfd);
// 允许端口快速重用
int reuse = 1;
if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
{
ERR_MSG("setsockopt");
return -1;
}
printf("允许端口快速重用成功\n");
// 填充地址信息结构体,
// 真实的地址信息结构体根据地址族指定 AF_INET:man 7 ip
struct sockaddr_in sin;
sin.sin_family = AF_INET; // 必须填AF_INET;
sin.sin_port = htons(PORT); // 端口号,1024~49151
sin.sin_addr.s_addr = inet_addr(IP); // 本机IP, ifconfig
// 将IP和端口绑定到套接字上;
if (bind(sfd, (struct sockaddr *)&sin, sizeof(sin)) < 0)
{
ERR_MSG("bind");
return -1;
}
printf("bind success __%d__\n", __LINE__);
// 将套接字设置为被动监听状态,监听是否有客户端连接成功;
if (listen(sfd, 128) < 0)
{
ERR_MSG("listen");
return -1;
}
printf("listen success __%d__\n", __LINE__);
int s_res = 0;
struct sockaddr_in cin; // 存储连接成功的客户端地址信息
socklen_t addrlen = sizeof(cin);
struct sockaddr_in saveCin[1024 - 4]; // 另存客户端地址信息,0,1,2,sfd不可能有对应的客户端
int epfd = epoll_create(1);
if (epfd < 0)
{
printf("epoll_create err\n");
exit(-1);
}
event.events = EPOLLIN;
event.data.fd = sfd;
ret = epoll_ctl(epfd, EPOLL_CTL_ADD, sfd, &event);
if (ret)
{
printf("epoll_ctl err\n");
exit(-1);
}
event.events = EPOLLIN;
event.data.fd = fd2;
ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd2, &event);
if (ret)
{
printf("epoll_ctl err\n");
exit(-1);
}
while (1)
{
ret = epoll_wait(epfd, events, 10, -1);
if (ret < 0)
{
printf("epoll_wait err\n");
exit(-1);
}
for (i = 0; i < ret; i++)
{
if (events[i].data.fd == sfd)
{
newsfd = accept(sfd, (struct sockaddr *)&cin, &addrlen);
if (sfd < 0)
{
ERR_MSG("accept");
return -1;
}
printf("[%s:%d] newfd=%d 连接成功__%d__\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newsfd, __LINE__);
event.events = EPOLLIN;
event.data.fd = newsfd;
ret = epoll_ctl(epfd, EPOLL_CTL_ADD, newsfd, &event);
}
else
{
bzero(buf, sizeof(buf));
//接收
res = recv(events[i].data.fd, buf, sizeof(buf), 0);
if(res < 0)
{
ERR_MSG("recv");
return -1;
}
if(res==0)
{
printf("[%s:%d] newfd=%d 客户端下线__%d__\n", \
inet_ntoa(saveCin[i-4].sin_addr), ntohs(saveCin[i-4].sin_port), i, __LINE__);
close(events[i].data.fd);
}
else
{
send(events[i].data.fd, buf, sizeof(buf), 0);
}
}
}
}
close(sfd);
return 0;
}