Advertisement
Zimnior69

non blocking server

Dec 5th, 2017
466
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #pragma comment (lib, "WS2_32.lib")
  2. #include <WinSock2.h>
  3. #include <windows.h>
  4. #include <iostream>
  5. #include <vector>
  6. std::vector<SOCKET> Connections;
  7. int main() {
  8.     WSADATA wsaData;
  9.     WSAStartup(MAKEWORD(2, 1), &wsaData);
  10.     SOCKADDR_IN addr;
  11.     int sizeofaddr = sizeof(addr);
  12.     addr.sin_addr.s_addr = INADDR_ANY;
  13.     addr.sin_port = htons(80);
  14.     addr.sin_family = AF_INET;
  15.     SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, NULL);
  16.     bind(listenSocket, (SOCKADDR*)(&addr), sizeofaddr);
  17.     listen(listenSocket, SOMAXCONN);
  18.     u_long iMode = 1;
  19.     ioctlsocket(listenSocket, FIONBIO, &iMode);
  20.     FD_SET readfds;
  21.     std::cout << "Running on 127.0.0.1:80..." << std::endl;
  22.     while (1) {
  23.         FD_ZERO(&readfds);
  24.         FD_SET(listenSocket, &readfds);
  25.         for (int i = 0; i < Connections.size(); i++) {
  26.             FD_SET(Connections[i], &readfds);
  27.         }      
  28.         select(0, &readfds, 0, 0, 0);
  29.         if (FD_ISSET(listenSocket, &readfds)) {
  30.             SOCKET newConnection = accept(listenSocket, NULL, NULL);
  31.             if (newConnection != INVALID_SOCKET) {
  32.                 std::cout << "new connection! N: " << (Connections.size() + 1) << std::endl;
  33.                 Connections.push_back(newConnection);
  34.             }
  35.         }
  36.         for (int i = 0; i < Connections.size(); i++) {
  37.             if (FD_ISSET(Connections[i], &readfds)) {
  38.                 char buffer[1024];
  39.                 int recvret = recv(Connections[i], buffer, 1024, 0);
  40.                 if (recvret == SOCKET_ERROR || recvret == 0) {
  41.                     if (WSAGetLastError() == WSAEWOULDBLOCK || recvret == 0) {
  42.                         std::cout << "Lost connection :(" << std::endl;
  43.                         closesocket(Connections[i]);
  44.                         continue;
  45.                     }
  46.                 }
  47.                 if (recvret > 0) {
  48.                     std::cout << "Got data from connection" << std::endl;
  49.                     char buf[] = "";
  50.                     send(Connections[i], buf, 4, 0);
  51.                 }
  52.             }
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement