Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //////////////////////
- #include "Server.h"
- int main()
- {
- Server myServer;
- while(true)
- {
- myServer.ListenForNewConnections();
- }
- return 0;
- }
- ///////////////////
- Server::Server()
- {
- ..................................................
- std::thread ph([this] { PacketSenderThread(); });// packet sender thread
- ph.detach();
- }
- /////////////////
- int Server::PacketSenderThread()
- {
- while (true) {
- std::lock_guard<std::mutex> lock(_mutex);
- for (auto& i : ConnHolder) {
- if (i->pmngr.HavePackets()) {
- Packet p = i->pmngr.Retrieve();
- if (!SendAllBytes(i, (char*)&p.buffer.front(), (int)p.buffer.size())) {
- std::cout << "Failed to send packet to client " << i << std::endl;
- }
- }
- }
- }
- return 0;
- }
- ///////////////////
- bool Server::ListenForNewConnections()
- {
- SOCKET newConnection = INVALID_SOCKET;
- newConnection = accept(ConnSock, (SOCKADDR*)&addr, &addrLen);
- if (newConnection == INVALID_SOCKET) {
- printf("Failed to accept connection. ERROR: %d\n", WSAGetLastError());
- return false;
- }
- else {
- std::lock_guard<std::mutex> lock(_mutex);
- ConnHolder.emplace_back(std::make_shared<Connection>(newConnection));
- ConnHolder.back()->ID = IDCounter;
- IDCounter += 1;
- std::cout << "Client Connected ID : " << IDCounter-1 << std::endl;
- std::thread ph([this] { UserMsgHandler(ConnHolder.back()); }); // packet handler thread
- ph.detach();
- return true;
- }
- }
- ///////////////////////
- int Server::UserMsgHandler(std::shared_ptr<Connection> connection)
- {
- PacketType ptype;
- while (true) {
- if (!RecvPacketType(connection, ptype)) {
- break;
- }
- if (!ProcessPacket(connection, ptype)) {
- break;
- }
- }
- std::cout << "Lost connection to client ID:" << connection->ID << std::endl;
- DisconnectClient(connection);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment