Home > Web > Publishing to CometD/Bayeux

Publishing to CometD/Bayeux

December 16th, 2011 Ed Leave a comment Go to comments

After following one of my two previous blog posts, you should be in a state ready to pub/sub to/from your web pages. Here’s a tiny bit of code that shows how you can push messages:

Thread t = new Thread(){
	int count = 0;
	@Override
	public void run() {
		while (true) {
			Mutable msg = bayeux.newMessage();
			msg.setChannel("/test");
			HashMap map = new HashMap();
			map.put("key1", count + "");
			msg.setData(map);

			ServerChannel c = bayeux.getChannel("/test");
			if (c != null) {
				c.publish(null, msg);
			}
			count++;
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
};
t.start();

I put that in the init() call of BayeuxInitialiser. Now when you subscribe to /test, you will get a message with an ever increasing value.

Very easy, very powerful. Would make a nice bridge between MQTT and the web, especially as it doesn’t rely on websockets etc.

Categories: Web Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.