Use the C language version of libev to implement a simple network communication server

Source: Internet
Author: User

The epoll server of the current network has encountered some strange problems recently. We have to use libev to quickly launch the server. Here we will record simple instances. Some bugs may exist in the Code. This code is not the code that runs online, but it is already full of code. If you have any questions, please discuss it together.

Reprinted with the source: http://blog.csdn.net/lengzijian/article/details/8315133

# Include <eV. h> # include <stdio. h> # include <netinet/in. h> # include <stdlib. h> # include <string. h> # Define Port 57789 # define buffer_size 2048 # define max_allowed_client 10240 struct ev_io * libevlist [empty] = {null}; void accept_cb (struct ev_loop * loop, struct ev_io * watcher, int revents); void read_cb (struct ev_loop * loop, struct ev_io * watcher, int revents); void timer_beat (struct ev_loop * loop, Struct ev_timer * watcher, int revents); int freelibev (struct ev_loop * loop, int FD); int main () {struct ev_loop * loop = ev_default_loop (0); int SD; struct sockaddr_in ADDR; int addr_len = sizeof (ADDR); // create an IO watcher and a timer watcher struct ev_io socket_accept; struct ev_timer timeout_w; // create socket connection SD = socket (pf_inet, sock_stream, 0); If (SD <0) {printf ("socket error \ n"); Return-1 ;} bzero (& add R, sizeof (ADDR); ADDR. sin_family = af_inet; ADDR. sin_port = htons (port); ADDR. sin_addr.s_addr = inaddr_any; // normal bind if (BIND (SD, (struct sockaddr *) & ADDR, sizeof (ADDR ))! = 0) {printf ("BIND error \ n"); Return-1;} // normal listen if (Listen (SD, somaxconn) <0) {printf ("Listen error \ n"); Return-1 ;}// set FD reusable int breuseaddr = 1; if (setsockopt (SD, sol_socket, so_reuseaddr, (const char *) & breuseaddr, sizeof (breuseaddr ))! = 0) {printf ("setsockopt error in reuseaddr [% d] \ n", SD); Return ;}// initialize Io watcher for listening to fd ev_io_init (& socket_accept, accept_cb, SD, ev_read); ev_io_start (loop, & socket_accept); // you can send a heartbeat packet to the remote end. // ev_timer_init (& timeout_w, timer_beat, 1 ., 0 .); // ev_timer_start (loop, & timeout_w); ev_run (loop, 0); return 1;} void accept_cb (struct ev_loop * loop, struct ev_io * watcher, int revents) {/* if there is a link, continue listening to fd; */ST Ruct sockaddr_in client_addr; socklen_t client_len = sizeof (client_addr); int client_sd; // create the client Io watcher struct ev_io * w_client = (struct ev_io *) malloc (sizeof (struct ev_io); If (w_client = NULL) {printf ("malloc error in accept_cb \ n"); return;} If (ev_error & revents) {printf ("error event in accept \ n"); return;} // get FD client_sd = accept (watcher-> FD, (struct sockaddr *) connected to the client *) & client_addr, & Client_len); If (client_sd <0) {printf ("Accept error \ n"); Return ;}// if the number of connections exceeds the specified range, close the connection if (client_sd> max_allowed_client) {printf ("FD too large [% d] \ n", client_sd); close (client_sd); return ;} if (libevlist [client_sd]! = NULL) {printf ("client_sd not null FD is [% d] \ n", client_sd); return;} printf ("Client Connected \ n "); // listen for new FD functions (w_client, read_cb, client_sd, ev_read); ev_io_start (loop, w_client); libevlist [client_sd] = w_client;} void read_cb (struct ev_loop * Loop, struct ev_io * watcher, int revents) {char buffer [buffer_size]; ssize_t read; If (ev_error & revents) {printf ("error event in read \ n"); return ;} // normal Recv READ = Recv (watcher-> FD, buffer, buffer_size, 0); If (read <0) {printf ("read error \ n "); return;} If (read = 0) {printf ("client disconnected. \ n "); // ev_io_stop (loop, Watcher); // free (watcher); // if the client is disconnected, release the response resource and disable monitoring freelibev (loop, watcher-> FD); return;} else {// buffer [read] = '\ 0'; printf ("Receive message: % s \ n", buffer );} // send (watcher-> FD, buffer, read, 0); bzero (buffer, read);} void timer_beat (struct ev_loop * loop, struct ev_timer * watcher, int revents) {float timeout = 2.0; // you can send a heartbeat packet or do nothing like printf ("Send beat per [% F] \ n", timeout ); fflush (stdout); If (ev_error & revents) {printf ("error event in timer_beat \ n"); return;} ev_timer_set (watcher, timeout, 0 .); ev_timer_start (loop, Watcher); return;} int freelibev (struct ev_loop * loop, int FD) {/* If (FD> max_allowed_client) {printf ("more than max_allowed_client [% d]", FD); Return-1;} * // clear related resources if (libevlist [FD] = NULL) {printf ("the FD already freed [% d] \ n", FD); Return-1;} Close (FD); ev_io_stop (loop, libevlist [FD]); free (libevlist [FD]); libevlist [FD] = NULL; return 1 ;}


 

Makefile:

CC=gccFLAGS=-I. -I/home/lengzijian/c/libev/libev-4.11 LDFLAGS=-L/usr/lib -L/home/lengzijian/c/libev/libev-4.11/.libs -lev -WallOBJECTS=server.oALL_BIN=serverall:$(ALL_BIN) $(ALL_BIN):$(OBJECTS) $(CC) $(FLAGS) $(LDFLAGS) -o $@ $^%.o:%.c$(CC) -c $< $(FLAGS) $(FLAGS)clean:rm -fr $(OBJECTS)rm -fr $(ALL_BIN)


 

Note the path of the header file in makefile and the path of the dynamic link library.

During the test, only Telnet IP 57789 is required.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.