用AsyncCtp实现一个简单的EchoServer

看到今天又支持SP1的AsyncCTP下载了,下载试用了一下,顺便写了一个EchoServer。

     static   void  Main( string [] args)
    {
        var listener 
=   new  TcpListener( new  IPEndPoint(IPAddress.Loopback,  3000 ));

        listener.Start();
        
while  ( true )
        {
            var client 
=  listener.AcceptTcpClient();

            TaskEx.Run(async () 
=>
                {
                    
using  (var stream  =  client.GetStream())
                    
using  (var writer  =   new  StreamWriter(stream) { AutoFlush  =   true  })
                    
using  (var reader  =   new  StreamReader(stream))
                    {
                        var line 
=   string .Empty;
                        
while  ((line  =   await reader.ReadLineAsync())  !=   null )
                        {
                            await writer.WriteAsync(
" >>>  "   +  line  +  Environment.NewLine);
                        }
                        Console.WriteLine(
" connection closed " );
                    }
                });
        }
    }

 

基本上和用同步的方式差不多,非常直接。

 

你可能感兴趣的:(server)