Advertisement
Tkap1

Untitled

Nov 3rd, 2024
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. s_list<SOCKET, 1024> socket_arr = zero;
  2. while(true) {
  3.  
  4.     WSAPOLLFD poll_arr[1025] = zero;
  5.     poll_arr[0].fd = server_socket;
  6.     poll_arr[0].events = POLLIN;
  7.     for(int socket_i = 0; socket_i < socket_arr.count; socket_i += 1) {
  8.         poll_arr[socket_i + 1].fd = socket_arr[socket_i];
  9.         poll_arr[socket_i + 1].events = POLLIN;
  10.     }
  11.  
  12.     int hot_socket_count = WSAPoll(poll_arr, socket_arr.count + 1, -1);
  13.     if(hot_socket_count < 0) {
  14.         error();
  15.     }
  16.  
  17.     int handled_count = 0;
  18.     int i = 0;
  19.     while(handled_count < hot_socket_count && i < 1025) {
  20.         SOCKET s = poll_arr[i].fd;
  21.         int flags = poll_arr[i].revents;
  22.         bool can_read = (flags & POLLRDNORM) || (flags & POLLRDBAND);
  23.         bool has_error = (flags & POLLERR) || (flags & POLLNVAL);
  24.         bool disconnected = flags & POLLHUP;
  25.         check(!has_error);
  26.         bool delete_socket = false;
  27.  
  28.         if(disconnected) {
  29.             printf("connection %i closed\n", i);
  30.             check(s != server_socket);
  31.             handled_count += 1;
  32.             delete_socket = true;
  33.         }
  34.  
  35.         else if(can_read) {
  36.             handled_count += 1;
  37.  
  38.             if(s == server_socket) {
  39.                 SOCKET new_socket = accept(server_socket, null, null);
  40.                 check(new_socket != INVALID_SOCKET);
  41.                 socket_arr.add(new_socket);
  42.             }
  43.             else {
  44.                 char buffer[65535 + 1];
  45.                 int bytes_read = recv(s, buffer, sizeof(buffer), 0);
  46.                 if(bytes_read > 0) {
  47.                 }
  48.                 else if(bytes_read == 0) {
  49.                     printf("connection clossed\n");
  50.                     delete_socket = true;
  51.                 }
  52.                 else {
  53.                     printf("recv failed\n");
  54.                     delete_socket = true;
  55.                 }
  56.             }
  57.         }
  58.  
  59.         if(delete_socket) {
  60.             shutdown(s, SD_BOTH);
  61.             closesocket(s);
  62.             socket_arr.remove_and_swap(i - 1);
  63.         }
  64.  
  65.         i += 1;
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement