// Server loop to handle incoming messages void UDPServer::loop(){ std::unique_lock<std::mutex> connectionLock(_mutex, std::defer_lock); sockaddr client_addr; // IP & port of other end of connection unsigned int client_size; char c; std::string str=""; const char *term=" \t\r\n"; while (!_dead) { if(skt_recvN_from(_socket,&c,1,&client_addr, &client_size) != 0){ stop(); // Stop on error } if (strchr(term,c)) { if (c=='\r') continue; /* will be CR/LF; wait for LF */ else{ connectionLock.lock(); // Create connection if needed if(_connections.count(to_string(client_addr)) == 0){ std::shared_ptr<UDPConnection> newCon = makeConnection(_socket, client_addr); newCon -> start(); _connections[to_string(client_addr)] = newCon; } // Push the message to the connection for handling ((UDPConnection*)(_connections[to_string(client_addr)].get())) -> push(str); connectionLock.unlock(); } } else str+=c; /* normal character--add to string and continue */ } }
bool TcpSocketServer::hasPendingSockets() const { if (!_listening) { return false; } std::lock_guard<std::mutex> connectionLock(_connectionMutex); return !_pendingConnections.empty(); }
std::unique_ptr<TcpSocket> TcpSocketServer::nextPendingTcpSocket() { if (!_listening) { return nullptr; } std::lock_guard connectionLock(_connectionMutex); if (!_pendingConnections.empty()) { std::unique_ptr<TcpSocket> connection = std::move(_pendingConnections.front()); _pendingConnections.pop_front(); return connection; } return nullptr; }
// Server loop to handle incoming connections void TCPServer::loop(){ std::unique_lock<std::mutex> connectionLock(_mutex, std::defer_lock); while(!_dead){ skt_ip_t client_ip; // IP & port of other end of connection unsigned int client_port; int cSocket = skt_accept(_socket, &client_ip, &client_port); sockaddr_in address = skt_build_addr(client_ip, client_port); sockaddr client_addr = *((sockaddr *)(&address)); connectionLock.lock(); std::shared_ptr<TCPConnection> newCon = makeConnection(cSocket, client_addr); newCon -> start(); _connections[to_string(client_addr)] = newCon; connectionLock.unlock(); } }
// Kill a connection by it's address void Server::kill(const sockaddr & connectionAddress){ std::unique_lock<std::mutex> connectionLock(_mutex, std::defer_lock); connectionLock.lock(); _connections.erase(to_string(connectionAddress)); connectionLock.unlock(); }