我正在构建一个使用Comet的网络应用程序。后端是用Atmosphere和Jersey建造的。但是,当我想订阅多个频道时,我遇到了麻烦。 jQuery插件氛围供应仅支持1个频道。我开始编写自己的实现,就像目前的彗星一样。
问题
如果我用msg“Hello”更新频道1,我不会收到通知。然而,当我用msg“World”更新频道2之后。我同时得到“你好”和“世界”......
var connection1 = new AtmosphereConnectionComet("http://localhost/b/product/status/1");
var connection2 = new AtmosphereConnectionComet("http://localhost/b/product/status/2");
var handleMessage = function(msg)
{
alert(msg);
};
connection1.NewMessage.add(handleMessage);
connection2.NewMessage.add(handleMessage);
connection1.connect();
connection2.connect();
AtmosphereConnectionComet实施:
更新的的
function AtmosphereConnectionComet(url)
{
//signals for dispatching
this.Connected = new signals.Signal();
this.Disconnected = new signals.Signal();
this.NewMessage = new signals.Signal();
//private vars
var xhr = null;
var self = this;
var gotWelcomeMessage = false;
var readPosition;
var url = url;
//private methods
var onIncomingXhr = function()
{
//check if we got some new data
if (xhr.readyState == 3)
{
//if the status is oke
if (xhr.status==200) // Received a message
{
//get the message
//this is like streaming.. each time we get readyState 3 and status 200 there will be text appended to xhr.responseText
var message = xhr.responseText;
console.log(message);
//check if we dont have the welcome message yet and if its maybe there... (it doesn't come in one pull)
if(!gotWelcomeMessage && message.indexOf("<--EOD-->") > -1)
{
//we has it
gotWelcomeMessage = true;
//dispatch a signal
self.Connected.dispatch(sprintf("Connected to %s", url));
}
//welcome message set, from now on only messages (yes this will fail for larger date i presume)
else
{
//dispatch the new message by substr from the last readPosition
self.NewMessage.dispatch(message.substr(readPosition));
}
//update the readPosition to the size of this message
readPosition = xhr.responseText.length;
}
}
//ooh the connection got resumed, seems we got disconnected
else if (xhr.readyState == 4)
{
//disconnect
self.disconnect();
}
}
var getXhr = function()
{
if ( window.location.protocol !== "file:" ) {
try {
return new window.XMLHttpRequest();
} catch(xhrError) {}
}
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch(activeError) {}
}
this.connect = function()
{
xhr = getXhr();
xhr.onreadystatechange = onIncomingXhr;
xhr.open("GET", url, true);
xhr.send(null);
}
this.disconnect = function()
{
xhr.onreadystatechange = null;
xhr.abort();
}
this.send = function(message)
{
}
}
更新9-1 23:00 GMT + 1
似乎气氛不输出东西..
ProductEventObserver
这是一个观察SEAM事件的ProductEventObserver。此组件已自动处理,位于SEAM的APPLICATION上下文中。它捕获事件并使用broadcastToProduct获取正确的广播器(通过broadcasterfactory)并将json消息(我使用gson作为json serializer / marshaller)广播到supspended连接。
package nl.ambrero.botenveiling.managers.product;
import com.google.gson.Gson;
import nl.ambrero.botenveiling.entity.product.Product;
import nl.ambrero.botenveiling.entity.product.ProductBid;
import nl.ambrero.botenveiling.entity.product.ProductBidRetraction;
import nl.ambrero.botenveiling.entity.product.ProductRetraction;
import nl.ambrero.botenveiling.managers.EventTypes;
import nl.ambrero.botenveiling.rest.vo.*;
import org.atmosphere.cpr.Broadcaster;
import org.atmosphere.cpr.BroadcasterFactory;
import org.atmosphere.cpr.DefaultBroadcaster;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.*;
import org.jboss.seam.log.Log;
@Name("productEventObserver")
@Scope(ScopeType.APPLICATION)
@AutoCreate
public class ProductEventObserver
{
@Logger
Log logger;
Gson gson;
@Create
public void init()
{
gson = new Gson();
}
private void broadCastToProduct(int id, ApplicationEvent message)
{
Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(DefaultBroadcaster.class, String.format("%s", id));
logger.info(String.format("There are %s broadcasters active", BroadcasterFactory.getDefault().lookupAll().size()));
if(broadcaster == null)
{
logger.info("No broadcaster found..");
return;
}
logger.info(String.format("Broadcasting message of type '%s' to '%s' with scope '%s'", message.getEventType(), broadcaster.getID(), broadcaster.getScope().toString()));
broadcaster.broadcast(gson.toJson(message));
}
@Observer(value = { EventTypes.PRODUCT_AUCTION_EXPIRED, EventTypes.PRODUCT_AUCTION_SOLD })
public void handleProductAcutionEnded(Product product)
{
this.broadCastToProduct(
product.getId(),
new ProductEvent(ApplicationEventType.PRODUCT_AUCTION_ENDED, product)
);
}
@Observer(value = EventTypes.PRODUCT_RETRACTED)
public void handleProductRetracted(ProductRetraction productRetraction)
{
this.broadCastToProduct(
productRetraction.getProduct().getId(),
new ProductRetractionEvent(ApplicationEventType.PRODUCT_RETRACTED, productRetraction)
);
}
@Observer(value = EventTypes.PRODUCT_AUCTION_STARTED)
public void handleProductAuctionStarted(Product product)
{
this.broadCastToProduct(
product.getId(),
new ProductEvent(ApplicationEventType.PRODUCT_AUCTION_STARTED, product)
);
}
@Observer(value = EventTypes.PRODUCT_BID_ADDED)
public void handleProductNewBid(ProductBid bid)
{
this.broadCastToProduct(
bid.getProduct().getId(),
new ProductBidEvent(ApplicationEventType.PRODUCT_BID_ADDED, bid)
);
}
@Observer(value = EventTypes.PRODUCT_BID_RETRACTED)
public void handleProductRetractedBid(ProductBidRetraction bidRetraction)
{
this.broadCastToProduct(
bidRetraction.getProductBid().getProduct().getId(),
new ProductBidRetractionEvent(ApplicationEventType.PRODUCT_BID_RETRACTED, bidRetraction)
);
}
}
Web.xml中
<servlet>
<description>AtmosphereServlet</description>
<servlet-name>AtmosphereServlet</servlet-name>
<servlet-class>org.atmosphere.cpr.AtmosphereServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>nl.ambrero.botenveiling.rest</param-value>
</init-param>
<init-param>
<param-name>org.atmosphere.useWebSocket</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>org.atmosphere.useNative</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AtmosphereServlet</servlet-name>
<url-pattern>/b/*</url-pattern>
</servlet-mapping>
atmosphere.xml
<atmosphere-handlers>
<atmosphere-handler context-root="/b" class-name="org.atmosphere.handler.ReflectorServletProcessor">
<property name="servletClass" value="com.sun.jersey.spi.container.servlet.ServletContainer"/>
</atmosphere-handler>
</atmosphere-handlers>
播音员:
@Path("/product/status/{product}")
@Produces(MediaType.APPLICATION_JSON)
public class ProductEventBroadcaster
{
@PathParam("product")
private Broadcaster product;
@GET
public SuspendResponse subscribe()
{
return new SuspendResponse.SuspendResponseBuilder()
.broadcaster(product)
.build();
}
}
更新10-1 4:18 GMT + 1
控制台输出:
16:15:16,623 INFO [STDOUT] 16:15:16,623 INFO [ProductEventObserver] There are 3 broadcasters active
16:15:16,624 INFO [STDOUT] 16:15:16,624 INFO [ProductEventObserver] Broadcasting message of type 'productBidAdded' to '2' with scope 'APPLICATION'
16:15:47,580 INFO [STDOUT] 16:15:47,580 INFO [ProductEventObserver] There are 3 broadcasters active
16:15:47,581 INFO [STDOUT] 16:15:47,581 INFO [ProductEventObserver] Broadcasting message of type 'productBidAdded' to '1' with scope 'APPLICATION'
答案 0 :(得分:1)
实际上,您发布的代码根本不起作用,因为AtmosphereConnectionComet
不会创建新对象。
function AtmosphereConnectionComet(url)
{
this.Connected = new signals.Signal();
this.Disconnected = new signals.Signal();
this.NewMessage = new signals.Signal();
这应该是一个构造函数,但你不是这样称呼它:
var connection1 = AtmosphereConnectionComet(...);
您必须使用new
关键字,因此它会像构造函数一样工作,否则this
内的AtmosphereConnectionComet
将不会引用 new 对象,但它会引用窗口对象(!)。
var connection1 = new AtmosphereConnectionComet(...);
现在你将真正拥有不同的连接,在第二次调用刚刚覆盖旧的东西之前。
了解Constructors和this在JavaScript中的工作原理。
更多问题
readPosition = this.responseText.length;
}
}
else if (this.readyState == 4)
那些this
应该是xhr
,而它们将起作用,因为函数在请求的上下文中被调用,为清楚起见,你应该坚持{{1} }或this
。
<强>更新强>
另一个错误。
xhr
答案 1 :(得分:1)
萨吕,
产品的价值:
@PathParam("product")
private Broadcaster product;
是否与broadCastToProduct(int id,ApplicationEvent消息)的id匹配?
发给我一个我可以看的测试用例(发布到users@atmosphere.java.net。
谢谢!
答案 2 :(得分:0)
我将我的项目发送给Jfarcand。他发现我使用的Atmosphere 0.6.3包含了ThreadPool的一个bug。这不应该是0.6.2。在0.7-SNAPSHOT中,它也是固定的,我认为他正在使用0.6.4修复错误的地方。