Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "Server.h"
- Server::Server() {
- port = 0;
- std::cout << "Enter port: " << std::endl;
- std::cin >> port;
- socket.bind(port);
- id = 0;
- socket.setBlocking(false);
- listenThread = std::thread(&Server::run, this);
- listenThread.join();
- }
- void Server::run() {
- sf::Packet packet;
- sf::IpAddress sender;
- unsigned short rport;
- std::cout << "server started!" << std::endl;
- sf::Clock deltaTime;
- while (true) {
- packet = sf::Packet();
- socket.receive(packet, sender, rport);
- unsigned short packetType = 0;
- unsigned short packetugid = 0;
- unsigned short cid = 0;
- packet >> packetugid >> packetType >> cid;
- if (packetugid == ugid) {
- for (auto &c : clients) {
- if (c.id == cid) {
- c.timeSinceLastPacket = sf::Time::Zero;
- std::cout << "Reset client tsp of " << c.id << " to 0" << std::endl;
- return;
- }
- }
- if (packetType == pt::handshake) {
- packet >> packetugid >> packetType;
- std::cout << sender << " joined the game!" << std::endl;
- id++;
- Client c;
- c.ip = sender;
- c.port = rport;
- c.id = id;
- clients.push_back(c);
- packet = sf::Packet();
- std::cout << id << std::endl;
- packet << ugid << pt::handshake << id;
- socket.send(packet, sender, rport);
- }
- }
- sf::Time dt = deltaTime.restart();
- for (Client &c : clients) {
- c.timeSinceLastPacket+= dt;
- if (c.timeSinceLastPacket.asSeconds() > 10) {
- std::cout << c.id << " has timed out!" << std::endl;
- removeClient(c.id);
- }
- }
- }
- }
- void Server::removeClient(unsigned short value) {
- /*std::list<Client>::iterator itri = clients.begin();
- while (itri != clients.end()) {
- if (itri->id == value) {
- itri = clients.erase(itri);
- } else {
- std::cout << "hey" << std::endl;
- ++itri;
- }
- }*/
- std::list<Client>::iterator i = clients.begin();
- while (i != clients.end())
- {
- if (i->id == value)
- {
- clients.erase(i++);
- }
- else
- {
- ++i;
- }
- }
- }
Add Comment
Please, Sign In to add comment