在昨天的随笔Reactive Extensions学习里,我写了个简单的stream异步读操作的扩展封装。今天我用它来实现了一个简单的EchoServer:
//一个简单的异步echo server
static void Main(string[] args)
{
var listener = new TcpListener(new IPEndPoint(IPAddress.Loopback, 3000));
listener.Start();
while (true)
{
var client = listener.AcceptTcpClient();
var stream = client.GetStream();
var writer = new StreamWriter(stream) { AutoFlush = true };
var buffer = new byte[1024];
stream.ReadLinesAsync(buffer)
.Select(line => ">>> " + line)
.Finally(client.Close)
.Subscribe(writer.WriteLine);
}
}
static void Main(string[] args)
{
var listener = new TcpListener(new IPEndPoint(IPAddress.Loopback, 3000));
listener.Start();
while (true)
{
var client = listener.AcceptTcpClient();
var stream = client.GetStream();
var writer = new StreamWriter(stream) { AutoFlush = true };
var buffer = new byte[1024];
stream.ReadLinesAsync(buffer)
.Select(line => ">>> " + line)
.Finally(client.Close)
.Subscribe(writer.WriteLine);
}
}
代码非常精简,比起以前的异步架构来说精简了不少。后续有时间的话再尝试用它重写一下以前的MSN客户端看看效果怎么样。