private void ReceiveData(IAsyncResult asyncResult) { try { ClientNode clientNode = clients.Find(x => x.tcpClient == (TcpClient)asyncResult.AsyncState); int toReadBytes = clientNode.tcpClient.GetStream().EndRead(asyncResult); if (toReadBytes == 0) { lock (clients) { OnClientDisconnected(clientNode); clientNode.tcpClient.Dispose(); clients.Remove(clientNode); } } else { OnDataReceived(clientNode, Encoding.ASCII.GetString(clientNode.RX, 0, toReadBytes).Trim()); clientNode.tcpClient.GetStream().BeginRead(clientNode.RX, 0, clientNode.RX.Length, ReceiveData, clientNode.tcpClient); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } }
public void WriteData(string message, ClientNode clientNode) { try { if (clientNode.tcpClient.Connected) { clientNode.TX = Encoding.ASCII.GetBytes(message); clientNode.tcpClient.GetStream().BeginWrite(clientNode.TX, 0, clientNode.TX.Length, OnCompleteWrite, clientNode.tcpClient); } } catch (Exception e) { throw new Exception(e.ToString()); } }
public void WriteData(string message, string endpoint) { ClientNode clientNode = clients.Find(x => x.tcpClient.Client.RemoteEndPoint.ToString() == endpoint); if (clientNode != null) { if (clientNode.tcpClient.Connected) { clientNode.TX = Encoding.ASCII.GetBytes(message); clientNode.tcpClient.GetStream().BeginWrite(clientNode.TX, 0, clientNode.TX.Length, OnCompleteWrite, clientNode.tcpClient); } } else { throw new KeyNotFoundException($"Client {endpoint} not found."); } }
public void RemoveClient(string endpoint) { ClientNode clientNode = clients.Find(x => x.tcpClient.Client.RemoteEndPoint.ToString() == endpoint); if (clientNode != null) { lock (clients) { OnClientDisconnected(clientNode); clientNode.tcpClient.Dispose(); clients.Remove(clientNode); } } else { throw new KeyNotFoundException($"Client {endpoint} not found."); } }
private void OnCompleteAcceptClient(IAsyncResult asyncResult) { try { if (listenerFlag) { ClientNode clientNode = new ClientNode(tcpListener.EndAcceptTcpClient(asyncResult)); lock (clients) { clients.Add(clientNode); } OnClientConnected(clientNode); clientNode.tcpClient.GetStream().BeginRead(clientNode.RX, 0, clientNode.RX.Length, ReceiveData, clientNode.tcpClient); tcpListener.BeginAcceptTcpClient(OnCompleteAcceptClient, tcpListener); } } catch (Exception e) { throw new Exception(e.ToString()); } }
protected virtual void OnDataSent(ClientNode node, string message) { DataSent?.Invoke(node, message); }
protected virtual void OnDataReceived(ClientNode node, string message) { DataReceived?.Invoke(node, message); }
protected virtual void OnClientDisconnected(ClientNode clientNode) { ClientDisconnected?.Invoke(clientNode); }