diff --git a/OpenPlayerIO/Connection.cs b/OpenPlayerIO/Connection.cs index a94c62f..e734e2c 100644 --- a/OpenPlayerIO/Connection.cs +++ b/OpenPlayerIO/Connection.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Linq; using System.Net; @@ -38,6 +38,8 @@ public class Connection private readonly byte[] _buffer = new byte[65536]; private readonly string _joinKey; + private bool _streamDisposed; + /// Send a message to the connected client. /// The message to send. public void Send(Message message) => _socket.Send(_serializer.Serialize(message)); @@ -71,6 +73,7 @@ public Connection(ServerEndpoint endpoint, string joinKey, MultiplayerProxy prox _socket.Connect(endpoint.Address, endpoint.Port); _stream = new NetworkStream(_socket); + _streamDisposed = false; _serializer = new BinarySerializer(); _deserializer = new BinaryDeserializer(); @@ -93,6 +96,8 @@ public Connection(ServerEndpoint endpoint, string joinKey, MultiplayerProxy prox private void ReceiveCallback(IAsyncResult ar) { + if (_streamDisposed) return; + var length = _stream.EndRead(ar); var received = _buffer.Take(length).ToArray(); @@ -100,11 +105,14 @@ private void ReceiveCallback(IAsyncResult ar) Terminate(new Exception("Connection unexpectedly terminated. (receivedBytes == 0)")); _deserializer.AddBytes(received); + + if (_streamDisposed) return; _stream.BeginRead(_buffer, 0, _buffer.Length, new AsyncCallback(this.ReceiveCallback), null); } private void Terminate(Exception exception) { + _streamDisposed = true; _stream.Close(); _socket.Disconnect(false); _socket.Close(); @@ -116,4 +124,4 @@ private void Terminate(Exception exception) else throw new PlayerIOError(ErrorCode.InternalError, string.Concat(new[] { "Connection from ", _endpoint.Address, " was closed. ", ", message: ", exception.Message })); } } -} \ No newline at end of file +}