Guest User

Untitled

a guest
Jan 19th, 2017
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. //////////////////////
  2. #include "Server.h"
  3. int main()
  4. {
  5.     Server myServer;
  6.  
  7.     while(true)
  8.     {
  9.         myServer.ListenForNewConnections();
  10.     }
  11.     return 0;
  12. }
  13. ///////////////////
  14. Server::Server()
  15. {
  16. ..................................................
  17.     std::thread ph([this] { PacketSenderThread(); });// packet sender thread
  18.     ph.detach();
  19. }
  20. /////////////////
  21. int Server::PacketSenderThread()
  22. {
  23.     while (true) {
  24.         std::lock_guard<std::mutex> lock(_mutex);
  25.         for (auto& i : ConnHolder) {
  26.             if (i->pmngr.HavePackets()) {
  27.                 Packet p = i->pmngr.Retrieve();
  28.                 if (!SendAllBytes(i, (char*)&p.buffer.front(), (int)p.buffer.size())) {
  29.                     std::cout << "Failed to send packet to client " << i << std::endl;
  30.                 }
  31.             }
  32.         }
  33.     }
  34.     return 0;
  35. }
  36. ///////////////////
  37. bool Server::ListenForNewConnections()
  38. {
  39.     SOCKET newConnection = INVALID_SOCKET;
  40.     newConnection = accept(ConnSock, (SOCKADDR*)&addr, &addrLen);
  41.     if (newConnection == INVALID_SOCKET) {
  42.         printf("Failed to accept connection. ERROR: %d\n", WSAGetLastError());
  43.         return false;
  44.     }
  45.     else {
  46.         std::lock_guard<std::mutex> lock(_mutex);
  47.         ConnHolder.emplace_back(std::make_shared<Connection>(newConnection));
  48.         ConnHolder.back()->ID = IDCounter;
  49.         IDCounter += 1;
  50.         std::cout << "Client Connected ID : " << IDCounter-1 << std::endl;
  51.         std::thread ph([this] { UserMsgHandler(ConnHolder.back()); }); // packet handler thread
  52.         ph.detach();
  53.         return true;
  54.     }
  55. }
  56.  
  57. ///////////////////////
  58. int Server::UserMsgHandler(std::shared_ptr<Connection> connection)
  59. {
  60.     PacketType ptype;
  61.     while (true) {
  62.         if (!RecvPacketType(connection, ptype)) {
  63.             break;
  64.         }
  65.         if (!ProcessPacket(connection, ptype)) {
  66.             break;
  67.         }
  68.     }
  69.     std::cout << "Lost connection to client ID:" << connection->ID << std::endl;
  70.     DisconnectClient(connection);
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment