基于网上很多对于 Reverse DWR 的误解,特别是普片认为 Polling 开销比 Comet 小的错误理解,因此撰写该文。
(该文的内容全部是基于DWR官网上的摘录。)
首先,我们看下官网上对 Polling,Comet 和 Piggyback 三者的对比
以下内容摘自 http://directwebremoting.org/dwr/documentation/reverse-ajax/index.html,并对部分内容加以翻译。
Comparison
Each method has some benefits.
Polling is simple to implement, however it can easily overload a server.(Polling 是最容易实现的,但是,它很容易 overload a server )In contrast Comet is a huge hack, but is much easier on servers.(反之,我们对比 comet,它就像是一个巨大的黑客(可以理解为“走后门一样”), 但是,它让 servers much easier ).Comet also scores by having very low latency - there is no need to wait for the next time the browser connects.(同样,Comet 具有 low latency(不占带宽) 的优势 - .........) Both polling and comet require extra network connectivity, so the really low overhead version is piggyback, but that can be very high latency.
( 可以看到,官网上对 Comet 的评价颇高,1)Much eaiser on servers, 2) Low Latency。而对 Polling 的方式不太推荐,easily overload a server. 并不是网上千篇一律的描述的 Polling 多么的具有优势, Comet 因为长时间占用connection而导致server性能多么的差。)
下面内容进一步对 Comet 进行了补充
Since Comet connections almost never last forever(因为 大多数Comet的connections不是永久存在的); for various reasons it is common to reconnect on a semi-regular basis(因为它通常可以在半途中重新连接,(如果连接中途断掉,那么可以重新连接)), Comet and Polling can be seen as extremes on a spectrum where there are 2 customizable parameters - the connected time and the disconnected time. DWR can manage these dynamically to help manage server load.(这里描述了两个非常重要的参数 connected time 和 disconnected time ,DWR 通过这两个参数来保证 server 不会被 overload )
( 可以看到,从官网大篇幅的介绍 Comet 的角度来看,它是极力推荐使用 Comet 来实现 Reverse Ajax,但是必须协同使用 connected time 和 disconnected time 来 manage server )
如何获取 HttpSession
HttpSession session = WebContextFactory.get().getSession();