服务器代码
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 + \ + (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 + \ + (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倍,在客户端⽐较少的时候两者⽆区别
因篇幅问题不能全部显示,请点此查看更多更全内容