10.3 回显服务器

  1. #include <event2/listener.h>
  2. #include <event2/bufferevent.h>
  3. #include <event2/buffer.h>
  4. #include <arpa/inet.h>
  5. #include <string.h>
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #include <errno.h>
  9. static void
  10. echo_read_cb(struct bufferevent *bev, void *ctx)
  11. {
  12. /* This callback is invoked when there is data to read on bev. */
  13. struct evbuffer *input = bufferevent_get_input(bev);
  14. struct evbuffer *output = bufferevent_get_output(bev);
  15. /* Copy all the data from the input buffer to the output buffer. */
  16. evbuffer_add_buffer(output, input);
  17. }
  18. static void
  19. echo_event_cb(struct bufferevent *bev, short events, void *ctx)
  20. {
  21. if (events & BEV_EVENT_ERROR)
  22. perror("Error from bufferevent");
  23. if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) {
  24. bufferevent_free(bev);
  25. }
  26. }
  27. static void
  28. accept_conn_cb(struct evconnlistener *listener,
  29. evutil_socket_t fd, struct sockaddr *address, int socklen,
  30. void *ctx)
  31. {
  32. /* We got a new connection! Set up a bufferevent for it. */
  33. struct event_base *base = evconnlistener_get_base(listener);
  34. struct bufferevent *bev = bufferevent_socket_new(
  35. base, fd, BEV_OPT_CLOSE_ON_FREE);
  36. bufferevent_setcb(bev, echo_read_cb, NULL, echo_event_cb, NULL);
  37. bufferevent_enable(bev, EV_READ|EV_WRITE);
  38. }
  39. static void
  40. accept_error_cb(struct evconnlistener *listener, void *ctx)
  41. {
  42. struct event_base *base = evconnlistener_get_base(listener);
  43. int err = EVUTIL_SOCKET_ERROR();
  44. fprintf(stderr, "Got an error %d (%s) on the listener. "
  45. "Shutting down.\n", err, evutil_socket_error_to_string(err));
  46. event_base_loopexit(base, NULL);
  47. }
  48. int
  49. main(int argc, char **argv)
  50. {
  51. struct event_base *base;
  52. struct evconnlistener *listener;
  53. struct sockaddr_in sin;
  54. int port = 9876;
  55. if (argc > 1) {
  56. port = atoi(argv[1]);
  57. }
  58. if (port<=0 || port>65535) {
  59. puts("Invalid port");
  60. return 1;
  61. }
  62. base = event_base_new();
  63. if (!base) {
  64. puts("Couldn't open event base");
  65. return 1;
  66. }
  67. /* Clear the sockaddr before using it, in case there are extra
  68. * platform-specific fields that can mess us up. */
  69. memset(&sin, 0, sizeof(sin));
  70. /* This is an INET address */
  71. sin.sin_family = AF_INET;
  72. /* Listen on 0.0.0.0 */
  73. sin.sin_addr.s_addr = htonl(0);
  74. /* Listen on the given port. */
  75. sin.sin_port = htons(port);
  76. listener = evconnlistener_new_bind(base, accept_conn_cb, NULL,
  77. LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
  78. (struct sockaddr*)&sin, sizeof(sin));
  79. if (!listener) {
  80. perror("Couldn't create listener");
  81. return 1;
  82. }
  83. evconnlistener_set_error_cb(listener, accept_error_cb);
  84. event_base_dispatch(base);
  85. return 0;
  86. }