Private Messages with cometD Chat

One of the common misconceptions regarding cometD, is that it can only do publish-subscribe messaging. While this misconception may be encouraged by the protocol design, it is definitely possible to do private messaging with cometD. In this article, I’ll look as some of the recent additions to the cometD chat demo and how they use private messages to implement member lists and private chat.

The basics of the cometd chat demo is definitely publish subscribe. All clients subscribe to the “/chat/demo” channel to receive chat, and publish to the same channel to send chat:

dojox.cometd.subscribe("/chat/demo", room, "_chat");
dojox.cometd.publish("/chat/demo", {
	user: room._username,
	join: true,
	chat: room._username + " has joined"
});

The cometD server is able to support this style of chat without any server-side chat specific components. But a chat room without a members list is a pretty basic chat room, and for that we need to introduce some server-side services to track members. For this demo, tracking members is a little harder than normal, because we are not running behind any authentication, so we cannot easily identify the user. If we had a real authentication mechanism in place, tracking users would simply be a matter of creating a ClientBayeuxListener instance and implementing the clientAdded and clientRemoved methods. So without authentication, the demo trusts the clients to tell us who they are in a join message.

So on the server, we create a ChatService that extends BayeuxService and registers to listen for all messages to chat channels:

  public class ChatService extends BayeuxService
  {
    private final ConcurrentMap<String, Map<String, String>> _members = 
      new ConcurrentHashMap<String, Map<String, String>>();
 
    public ChatService(Bayeux bayeux)
    {
      super(bayeux, "chat");
      subscribe("/chat/**", "trackMembers");
    }

This requests that the trackMembers method be called for all messages to “/chat/**”. This method is implemented to trigger on the join messages and to find/create a map of username to cometD clientId for each room encountered:

    public void trackMembers(final Client joiner, final String channelName, 
      Map<String, Object> data)
    {
      if (Boolean.TRUE.equals(data.get("join")))
      {
        Map<String, String> membersMap = _members.get(channelName);
        if (membersMap == null)
        {
          Map<String, String> newMembersMap = new 
            ConcurrentHashMap<String, String>();
          membersMap = _members.putIfAbsent(channelName, 
            newMembersMap);
          if (membersMap == null) membersMap = newMembersMap;
        }

The joining user is then added to the map of all users in the chat room and the updated set of all user names is published to the channel so that all clients receive the list:

        final String userName = (String)data.get("user");
        members.put(userName, joiner.getId());
        getBayeux().getChannel(channelName, false)
          .publish(getClient(), members.keySet(), null);

As well as joining the chat room, we need to track the leaving the chat room. The most reliable way to do this is to register a RemoveListener against the client, which is called if the client is removed from cometD for any reason:

        final Map<String, String> members = membersMap;
        joiner.addListener(new RemoveListener()
        {
          public void removed(String clientId, boolean timeout)
          {
            members.values().remove(clientId);
            Channel channel = getBayeux().getChannel(channelName, false);
            if (channel != null) 
              channel.publish(getClient(), members.keySet(), null);
          }
      });
    }
  }

So that was a little more involved that if we had an authentication mechanism, but it’s simple enough and we now have the server side tracking our users and maintaining a map between username and cometD clientID. This makes it relatively simple to add a service for private messages between users. We start by adding another subscription to the ChatService for private messages:

    public ChatService(Bayeux bayeux)
    {
        super(bayeux, "chat");
        subscribe("/chat/**", "trackMembers");
        subscribe("/service/privatechat", "privateChat");
    }

This subscribes the privateChat method to the channel “/service/privatechat”. Any channel in “/service/**” is special, in that it is not a broadcast publish/subscribe channel and any messages published is delivered only to the server or to clients that are explicitly called. In this case, clients publish to the privatechat channel and the messages are sent only to the server. The client JavaScript is updated to handle name::text as a way of sending a private message:

chat: function(text){
	var priv = text.indexOf("::");
	if (priv > 0) {
		dojox.cometd.publish("/service/privatechat", {
			room: "/chat/demo",
			user: room._username,
			chat: text.substring(priv + 2),
			peer: text.substring(0, priv)
		});
	} else {
		dojox.cometd.publish("/chat/demo", {
			user: room._username,
			chat: text
		});
	}
},

The privateChat service method is implemented to create a private message from the data passed and deliver it to the identified peer client and echo it back to the talking client:

  public void privateChat(Client source, String channel, 
    Map<String, Object> data,String id)
  {
    String room = (String)data.get("room");
    Map<String, String> membersMap = _members.get(room);
    String peerName = (String)data.get("peer");
    String peerId = membersMap.get(peerName);
    if (peerId!=null)
    {
      Client peer = getBayeux().getClient(peerId);
      if (peer!=null)
      {
        Map<String, Object> message = new HashMap<String, Object>();
	message.put("chat", data.get("chat"));
	message.put("user", data.get("user"));
	message.put("scope", "private");
	peer.deliver(getClient(), roomName, message, id);
	source.deliver(getClient(), roomName, message, id);
	return;
      }
    }
  }

The key code here are the calls to deliver on the source and peer Client instances. Unlike a call to Channel.publish(...), which will broadcast a message to all subscribers for a channel, a call to Client.deliver(...) will deliver the message to the channel handler only for that client. Thus both the source and the peer clients will receive the private message on the “/chat/demo” channel, but no other subscribers to the “/chat/demo” channel will receive that message.

It is the distinction between Channel.publish(...) and Client.deliver(...) that is the key to private messaging in cometD. Both use the channel to identify which handler(s) on the client will receive the message, but only the publish method uses the list of subscribers maintained by the server to determine which clients to deliver a published message to.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
智慧校园整体解决方案是响应国家教育信息化政策,结合教育改革和技术创新的产物。该方案以物联网、大数据、人工智能和移动互联技术为基础,旨在打造一个安全、高效、互动且环保的教育环境。方案强调从数字化校园向智慧校园的转变,通过自动数据采集、智能分析和按需服务,实现校园业务的智能化管理。 方案的总体设计原则包括应用至上、分层设计和互联互通,确保系统能够满足不同用户角色的需求,并实现数据和资源的整合与共享。框架设计涵盖了校园安全、管理、教学、环境等多个方面,构建了一个全面的校园应用生态系统。这包括智慧安全系统、校园身份识别、智能排课及选课系统、智慧学习系统、精品录播教室方案等,以支持个性化学习和教学评估。 建设内容突出了智慧安全和智慧管理的重要性。智慧安全管理通过分布式录播系统和紧急预案一键启动功能,增强校园安全预警和事件响应能力。智慧管理系统则利用物联网技术,实现人员和设备的智能管理,提高校园运营效率。 智慧教学部分,方案提供了智慧学习系统和精品录播教室方案,支持专业级学习硬件和智能化网络管理,促进个性化学习和教学资源的高效利用。同时,教学质量评估中心和资源应用平台的建设,旨在提升教学评估的科学性和教育资源的共享性。 智慧环境建设则侧重于基于物联网的设备管理,通过智慧教室管理系统实现教室环境的智能控制和能效管理,打造绿色、节能的校园环境。电子班牌和校园信息发布系统的建设,将作为智慧校园的核心和入口,提供教务、一卡通、图书馆等系统的集成信息。 总体而言,智慧校园整体解决方案通过集成先进技术,不仅提升了校园的信息化水平,而且优化了教学和管理流程,为学生、教师和家长提供了更加便捷、个性化的教育体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值