C#编写基于.Net IOCP的高性能服务器

无论什么平台,编写支持高并发性的网络服务器,瓶颈往往出在I/O上,目前最高效的是采用Asynchronous I/O模型,Linux平台提供了epoll,Windows平台提供了I/O Completion Port(IO完成端口,即IOCP)。

Windows自winsock2开始就提供了IOCP支持,可以通过C++直接调用API,但对于基于.Net的C#开发,是在.Net Framework2.0开始才引入的,在2.0版本下,最高效的网络服务器是通过异步Socket的一些列Beginxxx,Endxxx方法实现的, 底层就是基于IOCP的。

当.Net Framework升级到2.0 sp1之后,.Net Socket又提供了一种更高效的一些列xxxAsync方法,对底层IOCP实现性能有不少改进,.Net Framework升级到3.5之后更是成熟稳定,微软也开始大力推广。

在实际应用中,证明C#编写基于.Net IOCP的高性能服务器可以支持10000个以上的TCP长连接。但在具体实现过程中需要注意几个问题:
1.SocketAsyncEventArgs和Buffer最好预先分配,并能回收重复利用。
2.一个Socket的Send和Receive最好分别对应一个SocketAsyncEventArgs,因为当一个 SocketAsyncEventArgs被ReceiveAsync调用挂起后,在调用SendAsync时就会出异常。同样不要对一个 SocketAsyncEventArgs在一个异步操作被挂起时再次调用。

参考文章:
http://msdn.microsoft.com/zh-cn/magazine/cc163356.aspx
http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socketasynceventargs.aspx

49,064人评论了“C#编写基于.Net IOCP的高性能服务器”

  1. Admiring the time and energy you put into your site and detailed
    information you provide. It’s good to come across a blog every once in a while that isn’t the same out of date rehashed material.
    Fantastic read! I’ve bookmarked your site and I’m including your RSS
    feeds to my Google account.

  2. My brother recommended I may like this blog.
    He was once totally right. This put up actually made my
    day. You can not imagine just how much time I had spent for this info!
    Thank you!

  3. I like this site very much, Its a very nice post to read and incur info . “I’d better get off the phone now, I’ve already told you more than I heard myself.” by Loretta Lockhorn.

  4. I’m extremely impressed with your writing skills as well as with the layout on your weblog. Is this a paid theme or did you customize it yourself? Anyway keep up the excellent quality writing, it’s rare to see a nice blog like this one nowadays..

  5. That is very fascinating, You’re an overly skilled
    blogger. I have joined your rss feed and sit up for searching for extra
    of your great post. Additionally, I’ve shared your web site in my
    social networks

  6. Hi! This post couldn’t be written any better! Reading through this post reminds me of my good old room mate!

    He always kept talking about this. I will forward this page
    to him. Fairly certain he will have a good read.
    Thank you for sharing!

  7. Hey there, I think your website might be having browser compatibility issues.
    When I look at your blog in Opera, it looks fine but when opening in Internet Explorer, it has some overlapping.

    I just wanted to give you a quick heads up!

    Other then that, superb blog!

  8. Hi! I’m at work surfing around your blog from my new apple
    iphone! Just wanted to say I love reading your blog and look forward to all
    your posts! Keep up the great work!

发表评论

电子邮件地址不会被公开。 必填项已用*标注