You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.4 KiB

  1. 
  2. #include <iostream>
  3. #include<event2/event.h>
  4. #include <event2/listener.h>
  5. #include <string.h>
  6. #ifndef _WIN32
  7. #include <signal.h>
  8. #endif // !_WIN32
  9. #define SPORT 5001
  10. void listen_cb(struct evconnlistener *, evutil_socket_t, struct sockaddr *, int socklen, void *arg) {
  11. std::cout << "listen to be" << std::endl;
  12. }
  13. int main()
  14. {
  15. #ifdef _WIN32
  16. //初始化socket库
  17. WSADATA wsa;
  18. WSAStartup(MAKEWORD(2, 2), &wsa);
  19. #else
  20. if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { //忽略管道信号,发送数据给已关闭的socket,会飞掉!
  21. return 1;
  22. }
  23. #endif
  24. //创建libevent上下文
  25. event_base* base = event_base_new();
  26. if (base) {
  27. std::cout << "test server" << "\n";
  28. }
  29. sockaddr_in sin;
  30. memset(&sin, 0, sizeof(sin));
  31. sin.sin_family = AF_INET;
  32. sin.sin_port = htons(SPORT);
  33. //socket,bind listen 绑定事件
  34. evconnlistener * ev = evconnlistener_new_bind(base, //libevent上下文
  35. listen_cb, //接收到连接的回调函数
  36. base, //回调函数获取的参数(根据业务来)
  37. LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, //地址重用,evconnlistener关闭同时关闭socket
  38. 10, //连接队列大小,对应listen函数参数
  39. (sockaddr*)&sin,//绑定的地址和端口
  40. sizeof(sin)
  41. );
  42. if (base)
  43. event_base_dispatch(base); //事件分发处理
  44. if (ev)
  45. evconnlistener_free(ev); //清理
  46. if (base)
  47. event_base_free(base);
  48. #if _WIN32
  49. WSACleanup();
  50. #endif // _WIN32
  51. return 0;
  52. }