public AsyncTcpClient() { tcpClient = new TcpClient(); encoding = Encoding.Default; Conected = false; context = SynchronizationContext.Current; commands = CommonUtil.Commands.None; }
private void ReadCallback(IAsyncResult result) { int read; string message = string.Empty; NetworkStream networkStream; try { networkStream = tcpClient.GetStream(); read = networkStream.EndRead(result); } catch { //An error has occured when reading return; } if (read == 0) { //The connection has been closed. return; } byte[] buffer = result.AsyncState as byte[]; try { if (commands == CommonUtil.Commands.None) { byteMessage.Clear(); byte[] length = new byte[4]; Array.Copy(buffer, length, 4); uint i = length[0]; i = (i << 8) + length[1]; i = (i << 8) + length[2]; i = (i << 8) + length[3]; MessageLength = i + 4; commands = CommonUtil.Commands.ReadMessage; } switch (commands) { case CommonUtil.Commands.ReadMessage: byteMessage.AddRange(buffer); GetLength += buffer.Length; if (GetLength >= MessageLength) { byte[] inData = new byte[MessageLength]; Array.Copy(byteMessage.ToArray(), inData, inData.Length); context.Post(new SendOrPostCallback(MessageCallBack), (object)inData); commands = CommonUtil.Commands.None; } break; } } catch { } buffer = new byte[1024]; networkStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(ReadCallback), buffer); }