气氛一对一聊天

时间:2015-04-11 09:27:43

标签: java chat atmosphere

我刚开始使用Atmosphere进行简单的聊天应用程序。我用java下载了一个例子。此应用程序正在向所有客户端发送消息,如何向特定客户端发送消息。我想我能得到uuid。请有人指导我正确的方向。

   @Config
@ManagedService(path = "/chat", atmosphereConfig = MAX_INACTIVE + "=9990000")
public class Chat {
    private final Logger logger = LoggerFactory.getLogger(Chat.class);

    @Inject
    private BroadcasterFactory factory;

    @Heartbeat
    public void onHeartbeat(final AtmosphereResourceEvent event) {
        logger.trace("Heartbeat send by {}", event.getResource());
    }

    @Ready
    public void onReady(final AtmosphereResource r) {
        logger.info("Browser {} connected", r.uuid());
        if(null!=factory && null!=factory.getClass()){
            logger.info("BroadcasterFactory used {}", factory.getClass().getName());
        }

    }


    @Disconnect
    public void onDisconnect(AtmosphereResourceEvent event) {
        if (event.isCancelled()) {
            logger.info("Browser {} unexpectedly disconnected", event.getResource().uuid());
        } else if (event.isClosedByClient()) {
            logger.info("Browser {} closed the connection", event.getResource().uuid());
        }
    }


    @org.atmosphere.config.service.Message(encoders = {JacksonEncoder.class}, decoders = {JacksonDecoder.class})
     @DeliverTo(DeliverTo.DELIVER_TO.BROADCASTER)
    public Message onMessage(Message message) throws IOException {
        logger.info("{} just send {}", message.getAuthor(), message.getMessage());
        return message;
    }

}

1 个答案:

答案 0 :(得分:-1)

您的Java类不完整。

首先,有一个缺失变量,用于标识路径中的每个聊天室:

 @ManagedService(path = "/chat/{chatRoomId}", atmosphereConfig = MAX_INACTIVE + "=9990000")
  public class Chat {

     @PathParam("chatRoomId")
     private String chatRoomId;

     [...]
  }

但是,您可以将所有消息发送到仅连接的一个socke。

其次,你的脚本JS文件在哪里发送和接收websocket消息?

此脚本JS文件必须包含以下方法:

request.onOpen = function(request, response) {

};

request.onTransportFailure = function(request, response) {

};

request.onMessage = function(request, response) {

};

request.onClose = function(request, response) {

};

request.onError= function(request, response) {

};
request.onReconnect = function(request, response) {

};

最重要的是声明您的请求结构:

var socket = atmosphere;
var subSocket;
var transport = 'websocket';

var request = { 
    url: document.location.toString() + 'chat' + chatRoomId,
    contentType : "application/json",
    logLevel : 'debug',
    transport : transport ,
    trackMessageLength : true,
    reconnectInterval : 5000 
};