Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions OpenPlayerIO/Connection.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.IO;
using System.Linq;
using System.Net;
Expand Down Expand Up @@ -38,6 +38,8 @@ public class Connection
private readonly byte[] _buffer = new byte[65536];
private readonly string _joinKey;

private bool _streamDisposed;

/// <summary> Send a message to the connected client. </summary>
/// <param name="message"> The message to send. </param>
public void Send(Message message) => _socket.Send(_serializer.Serialize(message));
Expand Down Expand Up @@ -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();
Expand All @@ -93,18 +96,23 @@ 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();

if (length == 0)
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();
Expand All @@ -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 }));
}
}
}
}