From 976305f77e2359ca38de59364ca83ddb2791d248 Mon Sep 17 00:00:00 2001 From: SirJosh3917 Date: Thu, 2 Aug 2018 14:47:35 -0400 Subject: [PATCH] bool to check if the stream is closed fixes an issue where an exception would get thrown if the stream wasn't disposed, i'm not sure how thread safe this approach is but a try{}catch(ObjectDisposedException e){} seems ugly --- OpenPlayerIO/Connection.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) 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 +}