#include
#include
#include
#include
#include
#include
#include
#define TRACE_INT(v,fmt,args...) do {\
if(v < 0) {\
fprintf(stderr,fmt"\n",##args);\
return -1;\
}\
}while(0)
#define TRACE_POT(v,fmt,args...) do {\
if(v == NULL) {\
fprintf(stderr,fmt"\n",##args);\
return -1;\
}\
}while(0)
int32_t DEFAULT_LISTEN_PORT = 7123;
int32_t DEFAULT_LISTEN_SIZE = 100;
int32_t g_listen_port;
int32_t g_listen_size;
struct event_base *g_event_base;
void init_server_data()
{
g_listen_port = DEFAULT_LISTEN_PORT;
g_listen_size = DEFAULT_LISTEN_SIZE;
}
int init_server_socket(int32_t listen_port,int32_t listen_size)
{
int listen_fd ;
int on = 1;
int err = 0;
listen_fd = my_tcplisten(listen_port,listen_size);
TRACE_INT(listen_fd,"open tcp listen fail");
err = setsockopt(listen_fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
TRACE_INT(err,"setsockopt reuse address fail");
err = setsockopt(listen_fd,IPPROTO_TCP,TCP_NODELAY,&on,sizeof(on));
TRACE_INT(err,"setsockopt nodelay fail");
return listen_fd;
}
void server_loop(int listen_fd,short,void *)
{
char buf[100];
int cli_fd = my_accept(listen_fd,NULL,NULL);
if(read(cli_fd,buf,sizeof(buf))!=0)
{
fprintf(stdout,"%s\n",buf);
}
close(cli_fd);
return ;
}
int main()
{
int32_t socket_fd = 0;
init_server_data();
socket_fd = init_server_socket(g_listen_port,g_listen_size);
fprintf(stdout,"socket fd is %d\n",socket_fd);
g_event_base = event_base_new();
TRACE_POT(g_event_base,"new event base fail");
struct event listen_event;
event_set(&listen_event,socket_fd,EV_READ|EV_PERSIST,server_loop,NULL);
event_base_set(g_event_base,&listen_event);
event_add(&listen_event,NULL);
event_base_dispatch(g_event_base);
return 0;
}