现在的位置: 首页 > 综合 > 正文

java 高性能网络编程

2013年08月02日 ⁄ 综合 ⁄ 共 1337字 ⁄ 字号 评论关闭
 java.io.*

其是最原始的的最简的 IO 操作.
通常使用简单. 适合于并发数量不大的情况.
其 IO 时是阻塞的状态.
对于多SOCKET 来说可能要每SOCKET建立一个
Thread进行处理. 可想而有1000或更多的情况
下,服务器会成什么样子. 服务器都在忙于线程交换了.

java.nio.*
这是 Java 的异步IO 处理包. Socket 一般使用
select 的机制. 就是cpu 不断的查询所有的SOCKET
句柄,有事件它就报告. 比 java.io.* 有很大的进步
不过使用起来不是特别方便. 但是网上有许多的开源
NIO 框架可以使用. apahce MINA/windy 等. 使用方
法都差不多. 封装的很好.
但是显然这种情况CPU的占用率要高了.

iocp (windows), kqueue(freebsd), 或是 epoll(linux)
高性能的SOCKET.
一般的在线的网游都使用这些技术进行网络连接的架构.

听说 QQ Game 就是使用 epoll , 单台 Server 可以支持
万级别的Socket 连接. 汗了.

让人高兴的是 JDK6.0 开始支持 epoll 了.
A new java.nio.channels.SelectorProvider implementation that is based
on the Linux epoll event notification facility is included.
The epoll facility is available in the Linux 2.6, and newer,
kernels. The new epoll-based SelectorProvider implementation
is more scalable than the traditional poll-based SelectorProvider
implementation when there are thousands of SelectableChannels
registered with a Selector. The new SelectorProvider implementation
 will be used by default when the 2.6 kernel is detected.
The poll-based SelectorProvider will be used when a pre-2.6 kernel is detected.

网上看到 JDK5.0 已经有 epoll的实现了.
The epoll SelectorProvider will be included in 5.0 update 9.
To enable it requires setting the system property
java.nio.channels.spi.SelectorProvider to the value
sun.nio.ch.EPollSelectorProvider

总结:

java.io.*
相当于1000个民兵都去村口等着鬼子,来一个鬼子杀一个.
个人评论:村口地方小站不开呀!

select
相当于 一遍遍的询问“鬼子进村了吗?”,“鬼子进村了吗?”...
个人评论:烦呀,不干正经事,都磨嘴皮子了.

iocp (windows), kqueue(freebsd), 或是 epoll(linux)
一个人去村口站岗,等鬼子来,鬼子来去报告.

抱歉!评论已关闭.