#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#define PORT 8111
#define MESSAGE_LEN 1024
#define MAX_EVENTS 20
#define TIMEOUT 500
using std::cout;
using std::endl;
int main(int arc, char *argv[]) {
int ret = -1;
int socket_fd , accept_fd;
int on = 1;
int backlog = 10;
int flags = 1;
char in_buff[MESSAGE_LEN] = {0,};
struct sockaddr_in localaddr,remoteaddr;
struct epoll_event ev,events[MAX_EVENTS];
int epoll_fd;
int event_number;
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if (socket_fd == -1) {
cout << "Failed to create socket!" << endl;
exit(-1);
}
flags = fcntl(socket_fd,F_GETFL,0);
fcntl(socket_fd,F_SETFL,flags| O_NONBLOCK);
ret = setsockopt(socket_fd,
SOL_SOCKET,
SO_REUSEADDR,
&flags,
sizeof(flags));
if (ret == -1) {
cout << "Failed to set socket options" << endl;
}
localaddr.sin_family = AF_INET;
localaddr.sin_port = PORT;
localaddr.sin_addr.s_addr = INADDR_ANY;
ret = bind(socket_fd, (struct sockaddr *) &localaddr, sizeof(struct sockaddr));
if (ret == -1) {
cout << "Failed to bind addr!" << endl;
exit(-1);
}
ret = listen(socket_fd, backlog);
if (ret == -1) {
cout << " Failed to listen socket!" << endl;
exit(-1);
}
epoll_fd = epoll_create(256);
ev.events = EPOLLIN;
ev.data.fd = socket_fd;
epoll_ctl(epoll_fd,EPOLL_CTL_ADD,socket_fd,&ev);
for (;;) {
event_number = epoll_wait(epoll_fd,events,MAX_EVENTS,TIMEOUT);
for (int i = 0; i < event_number; ++i) {
if (events[i].data.fd == socket_fd){
socklen_t addr_len = sizeof(struct sockaddr_in);
accept_fd = accept(socket_fd,
(struct sockaddr *) &remoteaddr,
&addr_len);
flags = fcntl(accept_fd,F_GETFL,0);
fcntl(accept_fd,F_SETFL,flags| O_NONBLOCK);
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = accept_fd;
epoll_ctl(epoll_fd,EPOLL_CTL_ADD,accept_fd,&ev);
}else if (events[i].events & EPOLLIN){
do {
memset(in_buff,0,MESSAGE_LEN);
ret = recv(events[i].data.fd, (void *) in_buff, MESSAGE_LEN, 0);
if (ret == 0)
{
close(events[i].data.fd);
break;
}
if (ret == MESSAGE_LEN){
cout<< "maybe have data..."<<endl;
}
}while (ret<-1 && errno == EINTR);
if (ret <0){
switch (errno) {
case EAGAIN:
break;
case EINTR:
printf("recv EINTR... \n");
ret = recv(events[i].data.fd, &in_buff, MESSAGE_LEN, 0);
break;
default:
printf("the client is closed, fd:%d\n", events[i].data.fd);
epoll_ctl(epoll_fd, EPOLL_CTL_DEL, events[i].data.fd, &ev);
close(events[i].data.fd);
;
}
}
cout << "rev message:" << in_buff << endl;
send(events[i].data.fd, (void *) in_buff, MESSAGE_LEN, 0);
}
}
}
cout<<"quit server...\n"<<endl;
close(socket_fd);
return 0;
}
评论