diff --git a/components/net/cpp/src/universe.cpp b/components/net/cpp/src/universe.cpp index ed01d6fce4711136eae1a26d44dacf890b1ce75e..76b3e546ab3ff40027ec635167a9bbdd1f93c9fe 100644 --- a/components/net/cpp/src/universe.cpp +++ b/components/net/cpp/src/universe.cpp @@ -352,16 +352,22 @@ void Universe::_run() { { SHARED_LOCK(net_mutex_, lk); - //Also check each clients socket to see if any messages or errors are waiting + // Also check each clients socket to see if any messages or errors are waiting for (auto s : peers_) { if (s != NULL && s->isValid()) { - //If message received from this client then deal with it - if (FD_ISSET(s->_socket(), &sfdread_)) { - s->data(); - } - if (FD_ISSET(s->_socket(), &sfderror_)) { + // Note: It is possible that the socket becomes invalid after check but before + // looking at the FD sets, therefore cache the original socket + SOCKET sock = s->_socket(); + if (sock == INVALID_SOCKET) continue; + + if (FD_ISSET(sock, &sfderror_)) { s->socketError(); s->close(); + continue; // No point in reading data... + } + //If message received from this client then deal with it + if (FD_ISSET(sock, &sfdread_)) { + s->data(); } } }