Advertisement
Guest User

Untitled

a guest
Feb 20th, 2017
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. #include "Server.h"
  2.  
  3.  
  4.  
  5. Server::Server() {
  6.     port = 0;
  7.     std::cout << "Enter port: " << std::endl;
  8.     std::cin >> port;
  9.     socket.bind(port);
  10.  
  11.     id = 0;
  12.  
  13.     socket.setBlocking(false);
  14.  
  15.     listenThread = std::thread(&Server::run, this);
  16.     listenThread.join();
  17. }
  18.  
  19. void Server::run() {
  20.     sf::Packet packet;
  21.     sf::IpAddress sender;
  22.     unsigned short rport;
  23.  
  24.     std::cout << "server started!" << std::endl;
  25.     sf::Clock deltaTime;
  26.     while (true) {
  27.         packet = sf::Packet();
  28.         socket.receive(packet, sender, rport);
  29.  
  30.  
  31.         unsigned short packetType = 0;
  32.         unsigned short packetugid = 0;
  33.         unsigned short cid = 0;
  34.         packet >> packetugid >> packetType >> cid;
  35.         if (packetugid == ugid) {
  36.             for (auto c : clients) {
  37.                 if (c.id == cid) {
  38.                     //c.timeSinceLastPacket = 0;
  39.                     std::cout << "Reset client tsp of " << c.id << " to 0" << std::endl;
  40.                     return;
  41.                 }
  42.             }
  43.             if (packetType == pt::handshake) {
  44.                 packet >> packetugid >> packetType;
  45.                 std::cout << sender << " joined the game!" << std::endl;
  46.                 id++;
  47.  
  48.                 Client c;
  49.                 c.ip = sender;
  50.                 c.port = rport;
  51.                 //c.timeSinceLastPacket = 0;
  52.                 c.id = id;
  53.                
  54.                 clients.push_back(c);
  55.                 packet = sf::Packet();
  56.                 packet << ugid << pt::handshake << id << "The server greets you!";
  57.                 socket.send(packet, sender, rport);
  58.             }
  59.         }
  60.  
  61.         for (Client c : clients) {
  62.             c.timeSinceLastPacket++;
  63.             std::cout << c.timeSinceLastPacket << std::endl;
  64.         }
  65.     }
  66. }
  67.  
  68. void Server::removeClient(std::vector<Client> & clientvector, unsigned short id) {
  69.     clientvector.erase(
  70.         std::remove_if(clientvector.begin(), clientvector.end(), [&](Client const & client) {
  71.         return client.id == id;
  72.     }),
  73.         clientvector.end());
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement