/// <summary> /// Callback for the accept tcp client opertaion. /// </summary> /// <param name="result">The async result object</param> private void AcceptTcpClientCallback(IAsyncResult result) { TcpClient tcpClient = tcpListener.EndAcceptTcpClient(result); byte[] buffer = new byte[tcpClient.ReceiveBufferSize]; TCPClientInternal client = new TCPClientInternal(tcpClient, buffer); lock (this.clients) { this.clients.Add(client); } NetworkStream networkStream = client.NetworkStream; networkStream.BeginRead(client.Buffer, 0, client.Buffer.Length, ReadCallback, client); tcpListener.BeginAcceptTcpClient(AcceptTcpClientCallback, null); }
/// <summary> /// Callback for the read opertaion. /// </summary> /// <param name="result">The async result object</param> private void ReadCallback(IAsyncResult result) { TCPClientInternal client = result.AsyncState as TCPClientInternal; if (client == null || !client.TcpClient.Connected) { return; } int read; try { read = client.NetworkStream.EndRead(result); } catch (IOException) { read = 0; } if (read == 0) { lock (this.clients) { this.clients.Remove(client); return; } } string data = this.Encoding.GetString(client.Buffer, 0, read); this.NotifyDataReceived(client.TcpClient, data); //Do something with the data object here. client.NetworkStream.BeginRead(client.Buffer, 0, client.Buffer.Length, ReadCallback, client); }