Socket是一种双向管道文件

image.png

文件属性

首先Socket是一个文件,就有读和写。当线程想要读取客户端传输来的数据时,就从客户端 Socket 文件中读取数据;当线程想要发送数据到客户端时,就向客户端 Socket 文件中写入数据。服务端为了区分不同应用,通常需要记录端口、客户端IP等

轮询扫描

多个Socket对象可以看作是一个集合(数组 / 链表),扫描的过程就是主动轮询遍历这个集合,观察Socket对象的变化,如果用一个线程去做也被称作 I/O多路复用技术。

响应式(观察者模式)

与主动轮询相对应的,被动监听Socket对象的改变,所有文件的读写都会经过操作系统,这一步叫事件注册。举例在Linux 的三种典型的 I/O 多路复用模型中 select、poll、epoll 模型中,采用 epoll,底层既是红黑二叉搜索树

附 epoll 实现的示例服务

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/types.h>
  5. #include <sys/socket.h>
  6. #include <netdb.h>
  7. #include <unistd.h>
  8. #include <fcntl.h>
  9. #include <sys/epoll.h>
  10. #include <errno.h>
  11. #define MAXEVENTS 64
  12. static int
  13. make_socket_non_blocking (int sfd)
  14. {
  15. int flags, s;
  16. flags = fcntl (sfd, F_GETFL, 0);
  17. if (flags == -1)
  18. {
  19. perror ("fcntl");
  20. return -1;
  21. }
  22. flags |= O_NONBLOCK;
  23. s = fcntl (sfd, F_SETFL, flags);
  24. if (s == -1)
  25. {
  26. perror ("fcntl");
  27. return -1;
  28. }
  29. return 0;
  30. }
  31. static int
  32. create_and_bind (char *port)
  33. {
  34. struct addrinfo hints;
  35. struct addrinfo *result, *rp;
  36. int s, sfd;
  37. memset (&hints, 0, sizeof (struct addrinfo));
  38. hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */
  39. hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */
  40. hints.ai_flags = AI_PASSIVE; /* All interfaces */
  41. s = getaddrinfo (NULL, port, &hints, &result);
  42. if (s != 0)
  43. {
  44. fprintf (stderr, "getaddrinfo: %s\n", gai_strerror (s));
  45. return -1;
  46. }
  47. for (rp = result; rp != NULL; rp = rp->ai_next)
  48. {
  49. sfd = socket (rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  50. if (sfd == -1)
  51. continue;
  52. s = bind (sfd, rp->ai_addr, rp->ai_addrlen);
  53. if (s == 0)
  54. {
  55. /* We managed to bind successfully! */
  56. break;
  57. }
  58. close (sfd);
  59. }
  60. if (rp == NULL)
  61. {
  62. fprintf (stderr, "Could not bind\n");
  63. return -1;
  64. }
  65. freeaddrinfo (result);
  66. return sfd;
  67. }
  68. int
  69. main (int argc, char *argv[])
  70. {
  71. int sfd, s;
  72. int efd;
  73. struct epoll_event event;
  74. struct epoll_event *events;
  75. if (argc != 2)
  76. {
  77. fprintf (stderr, "Usage: %s [port]\n", argv[0]);
  78. exit (EXIT_FAILURE);
  79. }
  80. sfd = create_and_bind (argv[1]);
  81. if (sfd == -1)
  82. abort ();
  83. s = make_socket_non_blocking (sfd);
  84. if (s == -1)
  85. abort ();
  86. s = listen (sfd, SOMAXCONN);
  87. if (s == -1)
  88. {
  89. perror ("listen");
  90. abort ();
  91. }
  92. efd = epoll_create1 (0);
  93. if (efd == -1)
  94. {
  95. perror ("epoll_create");
  96. abort ();
  97. }
  98. event.data.fd = sfd;
  99. event.events = EPOLLIN | EPOLLET;
  100. s = epoll_ctl (efd, EPOLL_CTL_ADD, sfd, &event);
  101. if (s == -1)
  102. {
  103. perror ("epoll_ctl");
  104. abort ();
  105. }
  106. /* Buffer where events are returned */
  107. events = calloc (MAXEVENTS, sizeof event);
  108. /* The event loop */
  109. while (1)
  110. {
  111. int n, i;
  112. n = epoll_wait (efd, events, MAXEVENTS, -1);
  113. for (i = 0; i < n; i++)
  114. {
  115. if ((events[i].events & EPOLLERR) ||
  116. (events[i].events & EPOLLHUP) ||
  117. (!(events[i].events & EPOLLIN)))
  118. {
  119. /* An error has occured on this fd, or the socket is not
  120. ready for reading (why were we notified then?) */
  121. fprintf (stderr, "epoll error\n");
  122. close (events[i].data.fd);
  123. continue;
  124. }
  125. else if (sfd == events[i].data.fd)
  126. {
  127. /* We have a notification on the listening socket, which
  128. means one or more incoming connections. */
  129. while (1)
  130. {
  131. struct sockaddr in_addr;
  132. socklen_t in_len;
  133. int infd;
  134. char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
  135. in_len = sizeof in_addr;
  136. infd = accept (sfd, &in_addr, &in_len);
  137. if (infd == -1)
  138. {
  139. if ((errno == EAGAIN) ||
  140. (errno == EWOULDBLOCK))
  141. {
  142. /* We have processed all incoming
  143. connections. */
  144. break;
  145. }
  146. else
  147. {
  148. perror ("accept");
  149. break;
  150. }
  151. }
  152. s = getnameinfo (&in_addr, in_len,
  153. hbuf, sizeof hbuf,
  154. sbuf, sizeof sbuf,
  155. NI_NUMERICHOST | NI_NUMERICSERV);
  156. if (s == 0)
  157. {
  158. printf("Accepted connection on descriptor %d "
  159. "(host=%s, port=%s)\n", infd, hbuf, sbuf);
  160. }
  161. /* Make the incoming socket non-blocking and add it to the
  162. list of fds to monitor. */
  163. s = make_socket_non_blocking (infd);
  164. if (s == -1)
  165. abort ();
  166. event.data.fd = infd;
  167. event.events = EPOLLIN | EPOLLET;
  168. s = epoll_ctl (efd, EPOLL_CTL_ADD, infd, &event);
  169. if (s == -1)
  170. {
  171. perror ("epoll_ctl");
  172. abort ();
  173. }
  174. }
  175. continue;
  176. }
  177. else
  178. {
  179. /* We have data on the fd waiting to be read. Read and
  180. display it. We must read whatever data is available
  181. completely, as we are running in edge-triggered mode
  182. and won't get a notification again for the same
  183. data. */
  184. int done = 0;
  185. while (1)
  186. {
  187. ssize_t count;
  188. char buf[512];
  189. count = read (events[i].data.fd, buf, sizeof buf);
  190. if (count == -1)
  191. {
  192. /* If errno == EAGAIN, that means we have read all
  193. data. So go back to the main loop. */
  194. if (errno != EAGAIN)
  195. {
  196. perror ("read");
  197. done = 1;
  198. }
  199. break;
  200. }
  201. else if (count == 0)
  202. {
  203. /* End of file. The remote has closed the
  204. connection. */
  205. done = 1;
  206. break;
  207. }
  208. /* Write the buffer to standard output */
  209. s = write (1, buf, count);
  210. if (s == -1)
  211. {
  212. perror ("write");
  213. abort ();
  214. }
  215. }
  216. if (done)
  217. {
  218. printf ("Closed connection on descriptor %d\n",
  219. events[i].data.fd);
  220. /* Closing the descriptor will make epoll remove it
  221. from the set of descriptors which are monitored. */
  222. close (events[i].data.fd);
  223. }
  224. }
  225. }
  226. }
  227. free (events);
  228. close (sfd);
  229. return EXIT_SUCCESS;
  230. }