fix: #2536 NetworkServer won't accept connections while listen=false

This commit is contained in:
mischa 2024-10-14 15:10:05 +02:00 committed by mischa
parent 7ab1b394be
commit fe9bbcb6ac
2 changed files with 25 additions and 7 deletions

View File

@ -71,12 +71,7 @@ public static partial class NetworkServer
new Dictionary<uint, NetworkIdentity>();
/// <summary>Single player mode can set listen=false to not accept incoming connections.</summary>
static bool _listen = true;
public static bool listen
{
get { return _listen; }
set { _listen = value; }
}
public static bool listen;
// DEPRECATED 2024-10-14
[Obsolete("NetworkServer.dontListen was replaced with NetworkServer.listen. The new value is the opposite, and avoids double negatives like 'dontListen=false'")]
@ -685,6 +680,13 @@ static void OnTransportConnectedWithAddress(int connectionId, string clientAddre
static bool IsConnectionAllowed(int connectionId, string address)
{
// only accept connections while listening
if (!listen)
{
Debug.Log($"Server not listening, rejecting connectionId={connectionId} with address={address}");
return false;
}
// connectionId needs to be != 0 because 0 is reserved for local player
// note that some transports like kcp generate connectionId by
// hashing which can be < 0 as well, so we need to allow < 0!

View File

@ -1107,6 +1107,22 @@ public void UnSpawnAndClearAuthority()
Assert.That(comp.onStopAuthorityCalled, Is.EqualTo(1));
}
// test to prevent https://github.com/MirrorNetworking/Mirror/issues/2536
[Test]
public void SetListenToFalse()
{
// start the server with listen=true
NetworkServer.Listen(1);
// set listen=false at runtime
NetworkServer.listen = false;
// try connecting a client. should be reject while not listening.
NetworkClient.Connect("127.0.0.1");
UpdateTransport();
Assert.That(NetworkServer.connections.Count, Is.EqualTo(0));
}
// test to reproduce a bug where stopping the server would not call
// OnStopServer on scene objects:
// https://github.com/vis2k/Mirror/issues/2119
@ -1152,7 +1168,7 @@ public void ShutdownCleanup()
NetworkServer.Shutdown();
// state cleared?
Assert.That(NetworkServer.dontListen, Is.False);
Assert.That(NetworkServer.listen, Is.True);
Assert.That(NetworkServer.active, Is.False);
Assert.That(NetworkServer.isLoadingScene, Is.False);