/// Connects the connection to a server and begins listening.
/// </summary>
/// <param name="bytes">The bytes of data to send in the handshake.</param>
+ /// <param name="timeout">The number of milliseconds to wait before giving up on the connect attempt.</param>
/// <remarks>
/// Calling Connect makes the connection attempt to connect to the end point that's specified in the
/// constructor. This method will block until the connection attempt completes and will throw a
/// <see cref="HazelException"/> if there is a problem connecting.
/// </remarks>
- public abstract void Connect(byte[] bytes = null);
+ public abstract void Connect(byte[] bytes = null, int timeout = 5000);
/// <summary>
/// Invokes the DataReceived event.
/// <summary>
/// Blocks until the Connection is connected.
/// </summary>
+ /// <param name="timeout">The number of milliseconds to wait before timing out.</param>
/// <remarks>
/// This is a helper method for waiting until the connection is connected. It will block until the
/// <see cref="State"/> property is set to <see cref="ConnectionState.Connected"/> allowing the main thread to
/// wait until specific data is received etc. before returning to the user's code.
/// </remarks>
- protected void WaitOnConnect()
+ protected bool WaitOnConnect(int timeout)
{
- connectWaitLock.WaitOne();
+ return connectWaitLock.WaitOne(timeout);
}
/// <summary>
}
/// <inheritdoc />
- public override void Connect(byte[] bytes = null)
+ public override void Connect(byte[] bytes = null, int timeout = 5000)
{
lock(socketLock)
{
try
{
- socket.Connect(RemoteEndPoint);
+ IAsyncResult result = socket.BeginConnect(RemoteEndPoint, null, null);
+
+ result.AsyncWaitHandle.WaitOne(timeout);
+
+ socket.EndConnect(result);
}
catch (Exception e)
{
}
/// <inheritdoc />
- public override void Connect(byte[] bytes = null)
+ public override void Connect(byte[] bytes = null, int timeout = 5000)
{
lock(socketLock)
{
}
catch (SocketException e)
{
+ State = ConnectionState.NotConnected;
throw new HazelException("A socket exception occured while binding to the port.", e);
}
}
catch (SocketException e)
{
+ Dispose();
throw new HazelException("A Socket exception occured while initiating a receive operation.", e);
}
}
SendHello(bytes, () => { lock (socketLock) State = ConnectionState.Connected; });
//Wait till hello packet is acknowledged and the state is set to Connected
- WaitOnConnect();
+ bool timedOut = !WaitOnConnect(timeout);
+
+ //If we timed out raise an exception
+ if (timedOut)
+ {
+ Dispose();
+ throw new HazelException("Connection attempt timed out.");
+ }
}
/// <summary>
/// <remarks>
/// This will always throw a HazelException.
/// </remarks>
- public override void Connect(byte[] bytes)
+ public override void Connect(byte[] bytes = null, int timeout = 5000)
{
throw new HazelException("Cannot manually connect a UdpServerConnection, did you mean to use UdpClientConnection?");
}