using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Diagnostics; namespace AsyncTcpClient { class Program { TcpClient _client = null; NetworkStream _stream; byte[] _buf = new byte[2048]; StringBuilder _msg = new StringBuilder(); void OnRead(IAsyncResult ar) { int nRead = _stream.EndRead(ar); string data = Encoding.ASCII.GetString(_buf, 0, nRead); int lineno = 1; for (int k = 0; k < data.Length; ++k) { if (data[k] == '\n') { if (_msg.Length > 0) { if (_msg[_msg.Length - 1] == '\r') _msg.Remove(_msg.Length - 1, 1); if (_msg.Length > 0) Console.WriteLine("<<<< [{0}] {1}", lineno++, _msg.ToString()); _msg.Clear(); } } else _msg.Append(data[k]); } _stream.BeginRead(_buf, 0, _buf.Length, OnRead, null); } public void Run() { string host = "www.google.com"; int port = 80; _client = new TcpClient(host, port); if (!_client.Connected) { Console.WriteLine("Fail to connect to {0}:{1}", host, port); return; } _stream = _client.GetStream(); _msg.Capacity = 4098; _stream.BeginRead(_buf, 0, _buf.Length, OnRead, null); string cmd = "GET\n"; byte[] raw = Encoding.ASCII.GetBytes(cmd); Console.WriteLine("send " + cmd); _stream.Write(raw, 0, raw.Length); Console.ReadLine(); } static void Main(string[] args) { new Program().Run(); } } }
C# concise asynchronous TcpClient
最新推荐文章于 2025-03-23 20:33:02 发布