libev_echo.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include <sys/socket.h>
  7. #include <netinet/in.h>
  8. #include "ev.h"
  9. #define RECV_BUFSIZE 8192
  10. static char recvbuf[RECV_BUFSIZE];
  11. void do_recv(struct ev_loop *loop, struct ev_io *io, int revents) {
  12. int nread, nsend;
  13. nread = recv(io->fd, recvbuf, RECV_BUFSIZE, 0);
  14. if (nread <= 0) {
  15. goto error;
  16. }
  17. nsend = send(io->fd, recvbuf, nread, 0);
  18. if (nsend != nread) {
  19. goto error;
  20. }
  21. return;
  22. error:
  23. ev_io_stop(loop, io);
  24. close(io->fd);
  25. free(io);
  26. }
  27. void do_accept(struct ev_loop *loop, struct ev_io *listenio, int revents) {
  28. struct sockaddr_in peeraddr;
  29. socklen_t addrlen = sizeof(peeraddr);
  30. int connfd = accept(listenio->fd, (struct sockaddr*)&peeraddr, &addrlen);
  31. if (connfd <= 0) {
  32. return;
  33. }
  34. struct ev_io* io = (struct ev_io*)malloc(sizeof(struct ev_io));
  35. ev_io_init(io, do_recv, connfd, EV_READ);
  36. ev_io_start(loop, io);
  37. }
  38. int main(int argc, char** argv) {
  39. if (argc < 2) {
  40. printf("Usage: cmd port\n");
  41. return -10;
  42. }
  43. int port = atoi(argv[1]);
  44. struct sockaddr_in addr;
  45. int addrlen = sizeof(addr);
  46. memset(&addr, 0, addrlen);
  47. addr.sin_family = AF_INET;
  48. addr.sin_port = htons(port);
  49. int listenfd = socket(AF_INET, SOCK_STREAM, 0);
  50. if (listenfd < 0) {
  51. return -20;
  52. }
  53. if (bind(listenfd, (struct sockaddr*)&addr, addrlen) < 0) {
  54. return -30;
  55. }
  56. if (listen(listenfd, SOMAXCONN) < 0) {
  57. return -40;
  58. }
  59. struct ev_loop* loop = ev_loop_new(0);
  60. struct ev_io listenio;
  61. ev_io_init(&listenio, do_accept, listenfd, EV_READ);
  62. ev_io_start(loop, &listenio);
  63. ev_run(loop, 0);
  64. ev_loop_destroy(loop);
  65. return 0;
  66. }