服務器代碼
class Program { static int count = 0; static DateTime dt = DateTime.Now; static void Main(string[] args) { TcpListener server = new TcpListener(new IPEndPoint(IPAddress.Any, 11220)); server.Start(); // StartAcceptAsync(server); StartAccept(server); Console.Read(); } static void StartAcceptAsync(TcpListener s) { var v = s.AcceptTcpClientAsync(); v.ContinueWith((e) => { NetworkStream ns = e.Result.GetStream(); StartReadAsync(ns); StartAcceptAsync(s); Console.WriteLine("收到一個鏈接"); }); } static void StartReadAsync(NetworkStream ns) { byte[] buff = new byte[1024]; ns.ReadAsync(buff, 0, 1024).ContinueWith((e) => { if (count == 0) dt = DateTime.Now; try { count += e.Result; } catch { return;} Console.WriteLine("count=" + count + ",dt=" + (DateTime.Now - dt).TotalMilliseconds); StartReadAsync(ns); }); } static void StartAccept(TcpListener s) { Task.Run(() => { while (true) { TcpClient client = s.AcceptTcpClient(); StartRead(client.GetStream()); } }); } static void StartRead(NetworkStream ns) { Task.Run(() => { while (true) { if (count == 0) dt = DateTime.Now; byte[] data = new byte[1024]; try { int x = ns.Read(data, 0, 1024); count += x; } catch { return;} Console.WriteLine("count=" + count + ",dt=" + (DateTime.Now - dt).TotalMilliseconds); } }); } }
客戶端
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; namespace ConsoleApp4 { class Program { static int count = 0; static void Main(string[] args) { for (int i = 0; i < 10; i++) InitTcp(); Console.Read(); } static void InitTcp() { TcpClient tcp = new TcpClient(); tcp.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"),11220)); NetworkStream ns= tcp.GetStream(); Task.Run(() => { for (int i = 0; i < 10000; i++) { ns.WriteByte(0x01); count++; Console.WriteLine("Send Count=" + count); } }); } } }
同步
cpu :
結果:
異步
cpu:
結果:
異步與同步的 cpu占用差距不大可能我我模擬的客戶端不夠多的原因,
異步比同步接收的更快,
重新測試了100個客戶端 就出現問題,結果 同步遠遠低於異步,后來發現是 task 類 只使用了20個線程在調度,后改成 Thread 發現速度跟 異步基本一致
后修改threadpool的 最大最小線程數量 繼續使用 task,和異步 發現 task比之前的異步要快 ,但是同樣修改了線程數量以后的 異步 速度快了3倍左右
同線程數量 異步絕對快於同步 在線程少於客戶端連接時 異步大概是同步的100倍 線程多余 客戶端連接時 異步大概是 同步的 3倍,
在客戶端比較少的時候兩者無區別