/// <summary> /// Function that gets triggered when data a new client connects /// </summary> /// <param name="ar"></param> internal static void OnClientConnect(IAsyncResult ar) { var server = ar.AsyncState as EasyTcpServer; if (server?.BaseSocket == null || !server.IsRunning) { return; } try { var client = new EasyTcpClient(server.BaseSocket.EndAccept(ar)); client.OnDataReceive += (_, message) => server.FireOnDataReceive(message); client.OnDisconnect += (_, c) => server.FireOnDisconnect(c); client.OnError += (_, exception) => server.FireOnError(exception); client.StartListening(); server.FireOnConnect(client); if (client.BaseSocket != null) //Check if user aborted OnConnect with Client.Dispose() { lock (server.ConnectedClients) server.ConnectedClients.Add(client); } } catch (Exception ex) { server.FireOnError(ex); } server.BaseSocket.BeginAccept(OnClientConnect, server); //Accept next client }
/// <summary> /// Start listening for incoming data with the internal data receiver. /// This gets automatically called by the server and the Connect functions, but not when class is constructed with a socket. /// </summary> /// <param name="client"></param> /// <exception cref="Exception">client is already listening for incoming data</exception> public static void StartInternalDataReceiver(this EasyTcpClient client) { if (client.Buffer != null) { throw new Exception("Client is already listening for incoming data"); } client.StartListening(); }
/// <summary> /// Establishes a connection to a remote host /// </summary> /// <param name="client"></param> /// <param name="ipAddress">ipAddress of remote host</param> /// <param name="port">port of remote host</param> /// <returns>determines whether the client connected successfully</returns> public static async Task <bool> ConnectAsync(this EasyTcpClient client, IPAddress ipAddress, ushort port) { if (client == null) { throw new ArgumentException("Could not connect: client is null"); } if (ipAddress == null) { throw new ArgumentException("Could not connect: ipAddress is null"); } if (port == 0) { throw new ArgumentException("Could not connect: Invalid port"); } if (client.BaseSocket != null) { throw new ArgumentException("Could not connect: client is still connected"); } try { client.BaseSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); await client.BaseSocket.ConnectAsync(ipAddress, port); if (client.BaseSocket.Connected) { client.FireOnConnect(); client.StartListening(); return(true); } } catch { //Ignore exception, dispose (&disconnect) client and return false } client.Dispose(); return(false); }