/// <summary> /// Raised by the underlying <see cref="Connection"/> when a connection is established /// </summary> private void Connection_ConnectedEvent(object sender, EventArgs e) { // Just pass on the event along var args = new object[] { sender, e }; ConnectedEvent.RaiseEventSafe(ref args); }
/// <summary> /// Raised by the socket wrapper when a connection is successfully made /// </summary> private void ClientInstance_ConnectedEvent(object sender, EventArgs e) { Logger.Log(Logger.Level.Info, "Connection to the server made successfully. Passing on...."); // Pass the event on var args = new object[] { sender, e }; ConnectedEvent.RaiseEventSafe(ref args); }
/// <summary> /// Establish the connection to the server. /// </summary> /// <param name="RemoteIP">The server IP address.</param> /// <param name="Port">The TCP port on which to connect.</param> /// <param name="ConnectionTimeout">The timeout for this operation in milliseonds</param> public void Connect(IPAddress RemoteIP, int Port, int ConnectionTimeout = 5000) { Logger.Log(Logger.Level.Info, "Attempting connection to the remote socket"); try { if (Port < 0) { throw new ArgumentException("Negative values not supported.", nameof(Port)); } if (ConnectionTimeout < 0) { throw new ArgumentException("ConnectionTimeout must be zero or greater.", nameof(ConnectionTimeout)); } this.RemoteIP = RemoteIP ?? throw new ArgumentNullException("Null values are not supported", nameof(RemoteIP)); this.Port = Port; TokenSource = new CancellationTokenSource(); Client = new System.Net.Sockets.TcpClient(); Logger.Log(Logger.Level.Debug, $"Timeout: {ConnectionTimeout}"); Logger.Log(Logger.Level.Debug, "Beginning socket connection"); var ar = Client.BeginConnect(RemoteIP, Port, null, null); try { if (!ar.AsyncWaitHandle.WaitOne(ConnectionTimeout, false)) { Client.Close(); throw new TimeoutException($"Timeout connecting to {this.RemoteIP}:{this.Port}"); } Client.EndConnect(ar); Logger.Log(Logger.Level.Info, "Connection to remote socket succeeded"); NetworkStream = Client.GetStream(); Connected = true; } catch (Exception) { throw; } finally { ar.AsyncWaitHandle.Close(); } Logger.Log(Logger.Level.Info, $"Raising the {nameof(ConnectedEvent)} event"); var args = new object[] { this, EventArgs.Empty }; ConnectedEvent.RaiseEventSafe(ref args); Logger.Log(Logger.Level.Info, $"Starting socket monitoring"); DataReceiverLoop = Task.Run(() => DataReceiver(Token), Token); } catch (Exception ex) { Logger.Log(Logger.Level.Error, $"Failed to connect to the remote socket.\n\n{ex.Message}"); throw; } }