首页 / 软件开发 / .NET编程技术 / 使用.net3.5的缓存池和SocketAsyncEventArgs类创建socket服务器
使用.net3.5的缓存池和SocketAsyncEventArgs类创建socket服务器2011-07-23 博客园 蛙蛙池塘在.NET 3.5里System.Net.Sockets空间下有一组增强功能的类,提供可供专用的高性能套接字应用程 序使用的可选异步模式,SocketAsyncEventArgs 类就是这一组增强功能的一部分。该类专为需要高性能 的网络服务器应用程序而设计。应用程序可以完全使用增强的异步模式,也可以仅仅在目标热点区域(例 如,在接收大量数据时)使用此模式。以下是关于此类的介绍(摘自MSDN)http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socketasynceventargs.aspx其实主要是改进了异步模式,让一些类可以重用,可能用的对象池的原理,不像以前的异步传输模式 ,每个数据来了,new一个新的iasyncresult,这样可能会引起GC线程CPU很高。下面是我找的一篇介 绍.net 3.5里增强的socket api使用的文章,我翻译了一下,大家了解一下,貌似性能增强了不少。当然 大家肯定说还不如看原文呢,但怎么说也是俺花了好几天,问了好多人才翻译出来的,大家没事赏个脸看 看也没啥坏处,对吧。原文链接如下(未经作者同意翻译的,我不知道怎么联系作者,也不会用英语和作 者交流,如果作者会中文,我就会问问他是否让我翻译)http://www.flawlesscode.com/post/2008/01/Socket-Server-with-Net35-using- SocketAsyncEventArgs.aspxIn a previous post I talked about the System.Net.Sockets enhancements in .NET 3.5, and if you haven"t read it I suggest you do before tucking in to this as some of that code is important to understand what"s happening here.在前面的帖子里,我谈到了System.Net.Sockets在.NET 3.5里的增强,如果你还没有读过,我建议你 深入本帖之前先读一下,因为那些代码对理解本帖很重要。Before I start, in essence this is just a result of my experimentation and while it seems it does a pretty good job,在开始之前(我有必要提一下),虽然它看起来不错,但这本质上只是我实验的一个结果,。I"m not going to claim it"s bullerproof or that it"s a good example of how to write a socket server all it does is demonstrate the techniques of working with the new classes and methods.我不想声称这是bullerproof的,或者是一个很好的关于如何编写socket服务器的例子,所有这些用于 演示使用新的类和方法工作的技术。The sample solution you can see on the right there contains three projects.你可以在右边看到示例解决方案里有三个项目。FlawlessCode contains all the classes we"ll need to build ourselves a socket server.FlawlessCode项目包含了创建Socket服务器所需的所有的类。TestLoadGenerator is a console application which generates load for us by connecting lots of sockets to our server and sending it random data.TestLoadGenerator项目用于向我们的Socket服务器产生大量的socket连接负载,并向服务器发送随机 数据。TestSocketServer is a small socket server implementation using the classes in FlawlessCode.TestSocketServer项目是一个使用FlawlessCode项目实现的一个简单的Socket服务端。TcpSocketListenerWe"ll begin by looking at the FlawlessCode project and in particular, the TcpSocketListener.我们将从FlawlessCode项目开始,特别是TcpSocketListener类。It should be fairly obvious from the name what this class is meant to achieve, it sits in a loop listening for socket connections and lets us know when one arrives.从名称上很容易看出这个类的功能,它在一个循环里监听socket连接,并在连接到达时通知我们。The public interface is very simple and looks like this: