-using System;
+using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Hazel;
mutex2.WaitOne();
}
+ /// <summary>
+ /// Ensures a client sends a disconnect packet to the server on Dispose.
+ /// </summary>
+ /// <param name="listener">The listener to test.</param>
+ /// <param name="connection">The connection to test.</param>
+ internal static void RunClientDisconnectOnDisposeTest(NetworkConnectionListener listener, Connection connection)
+ {
+ ManualResetEvent mutex = new ManualResetEvent(false);
+ ManualResetEvent mutex2 = new ManualResetEvent(false);
+
+ listener.NewConnection += delegate (NewConnectionEventArgs args)
+ {
+ args.Connection.Disconnected += delegate (object sender2, DisconnectedEventArgs args2)
+ {
+ mutex2.Set();
+ };
+
+ mutex.Set();
+ };
+
+ listener.Start();
+
+ connection.Connect();
+
+ if (!mutex.WaitOne(TimeSpan.FromSeconds(1)))
+ {
+ Assert.Fail("Timeout waiting for client connection");
+ }
+
+ connection.Dispose();
+
+ if (!mutex2.WaitOne(TimeSpan.FromSeconds(1)))
+ {
+ Assert.Fail("Timeout waiting for client disconnect packet");
+ }
+ }
+
/// <summary>
/// Builds new data of increaseing value bytes.
/// </summary>
}
}
+ /// <summary>
+ /// Test that a disconnect is sent when the client is disposed.
+ /// </summary>
+ public void ClientDisconnectOnDisposeTest()
+ {
+ using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
+ using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
+ {
+ TestHelper.RunClientDisconnectOnDisposeTest(listener, connection);
+ }
+ }
+
/// <summary>
/// Tests disconnection from the server.
/// </summary>
}
}
+ /// <summary>
+ /// Test that a disconnect is sent when the client is disposed.
+ /// </summary>
+ public void ClientDisconnectOnDisposeTest()
+ {
+ using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
+ using (UdpConnection connection = new UnityUdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
+ {
+ TestHelper.RunClientDisconnectOnDisposeTest(listener, connection);
+ }
+ }
+
/// <summary>
/// Tests disconnection from the server.
/// </summary>
public class UnityUdpClientConnection : UdpConnection
{
private Socket socket;
+ private bool sendSynchronously = false;
public UnityUdpClientConnection(IPEndPoint remoteEndPoint, IPMode ipMode = IPMode.IPv4)
: base()
{
try
{
- socket.BeginSendTo(
- bytes,
- 0,
- length,
- SocketFlags.None,
- EndPoint,
- HandleSendTo,
- null);
+ if (this.sendSynchronously)
+ {
+ socket.SendTo(
+ bytes,
+ 0,
+ length,
+ SocketFlags.None,
+ EndPoint);
+ }
+ else
+ {
+ socket.BeginSendTo(
+ bytes,
+ 0,
+ length,
+ SocketFlags.None,
+ EndPoint,
+ HandleSendTo,
+ null);
+ }
}
catch (NullReferenceException) { }
catch (ObjectDisposedException)
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
+ this.sendSynchronously = true;
+
if (disposing)
{
SendDisconnect();