栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用.Net 4.5异步功能进行套接字编程

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用.Net 4.5异步功能进行套接字编程

…由于您是如此坚决,我整理了一个非常简单的示例,说明如何编写回显服务器以助您一臂之力。收到的任何内容都会回显给客户端。服务器将保持运行60秒。尝试在localhost端口6666上远程登录到它。花一些时间来确切了解这里发生的情况。

void Main(){    CancellationTokenSource cts = new CancellationTokenSource();    TcpListener listener = new TcpListener(IPAddress.Any, 6666);    try    {        listener.Start();        //just fire and forget. We break from the "forgotten" async loops        //in AcceptClientsAsync using a CancellationToken from `cts`        AcceptClientsAsync(listener, cts.Token);        Thread.Sleep(60000); //block here to hold open the server    }    finally    {        cts.Cancel();        listener.Stop();    }}async Task AcceptClientsAsync(TcpListener listener, CancellationToken ct){    var clientCounter = 0;    while (!ct.IsCancellationRequested)    {        TcpClient client = await listener.AcceptTcpClientAsync().ConfigureAwait(false);        clientCounter++;        //once again, just fire and forget, and use the CancellationToken        //to signal to the "forgotten" async invocation.        EchoAsync(client, clientCounter, ct);    }}async Task EchoAsync(TcpClient client,          int clientIndex,          CancellationToken ct){    Console.WriteLine("New client ({0}) connected", clientIndex);    using (client)    {        var buf = new byte[4096];        var stream = client.GetStream();        while (!ct.IsCancellationRequested)        { //under some circumstances, it's not possible to detect //a client disconnecting if there's no data being sent //so it's a good idea to give them a timeout to ensure that  //we clean them up. var timeoutTask = Task.Delay(TimeSpan.FromSeconds(15)); var amountReadTask = stream.ReadAsync(buf, 0, buf.Length, ct); var completedTask = await Task.WhenAny(timeoutTask, amountReadTask)         .ConfigureAwait(false); if (completedTask == timeoutTask) {     var msg = Encoding.ASCII.GetBytes("Client timed out");     await stream.WriteAsync(msg, 0, msg.Length);     break; } //now we know that the amountTask is complete so //we can ask for its Result without blocking var amountRead = amountReadTask.Result; if (amountRead == 0) break; //end of stream. await stream.WriteAsync(buf, 0, amountRead, ct)  .ConfigureAwait(false);        }    }    Console.WriteLine("Client ({0}) disconnected", clientIndex);}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465472.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号