为什么我得到这个例外,“Deflator已关闭”[Websockets]

时间:2017-09-18 18:34:30

标签: java exception websocket

我正在像facebook那样实现聊天应用程序。

一对一聊天完成了声音,通知和消息计数器。

但在聊天的某个时刻我遇到了这个错误

enter image description here

这是我的ChatSocket.js班级

var chatsocket = function() {

var messageReceive = "";

var ws;

var messageSend = function(message) {
    var buildMessage = "<div class='row msg_container base_sent'>"
            + "<div class='col-md-10 col-xs-10'> "
            + "<div class='messages msg_sent'>" + "<p>" + message + "</p>"
            + "<time datetime='2009-11-13T20:00'>Timothy • 51 min</time>"
            + "</div>" + "</div>" + "";
    var imgMessage = "<div  class='col-md-2 col-xs-2 avatar'>"
            + "<img src='http://www.bitrebels.com/wp-content/uploads/2011/02/Original-Facebook-Geek-Profile-Avatar-1.jpg'class='img-responsive ' />"
            + "</div>" + "</div>";
    return buildMessage + imgMessage;
};

var messageReceive = function(message) {
    var imgMessage = "<div class='row msg_container base_receive'>" +
            "<div  class='col-md-2 col-xs-2 avatar'>"
            + "<img src='http://www.bitrebels.com/wp-content/uploads/2011/02/Original-Facebook-Geek-Profile-Avatar-1.jpg'class='img-responsive ' />"
            + "</div>";

    var buildMessage = "<div class='col-md-10 col-xs-10'> "
        + "<div class='messages msg_receive'>" + "<p>" + message + "</p>"
        + "<time datetime='2009-11-13T20:00'>Timothy • 51 min</time>"
        + "</div>" + "</div>" + "</div>";
    return imgMessage + buildMessage;
};

var connect = function() {
    var user = $("#user").val();
    try{
        ws = new WebSocket("ws://localhost:8080/EnterpriceChat/chat/" + user);
    } catch(err) {          
        console.log("error");
    }
    ws.onmessage = function(event) {
        var message = JSON.parse(event.data);
        //Refresh the list since there is a user which is online/offline now
        if(message.content == 'refreshContact') {
            loadUserContactList();
        } else {
            var idSuffix = getElementIdSuffix(message.from);
            var status = createNewChatBox(message.from);                
            if(!status) {
                var msg_panel_id = getMsgPanelId(idSuffix);         
                $("#"+msg_panel_id).append(messageReceive(message.content));
            }
            scrollToBottom(message.from);
            updateNotification(message.from);
        }
    };

};

var sendMessage = function(element) {
    var inputElementId = element.attr("data-id");
    var to = element.attr("data-id-email");
    var msg_panel_id = element.attr("data-id-msg-panel");

    //Validating the inputs
    var content = $("#"+inputElementId).val();
    //Reset the input fields
    $("#"+inputElementId).val('');
    if(!content) {
        return;
    }

    var json = JSON.stringify({
        "to" : to,
        "content" : content
    });

    ws.send(json);
    $("#"+msg_panel_id).append(messageSend(content));
};

var eventClick = function() {
    $('.btn-chat-send').unbind('click');        
    $('.chat_input').unbind('keypress');
    $('.chat_input').unbind('focus');
    $('#userListCategory').find('li').unbind('click');
    $('.user_list_entry').unbind('click');      

    $('.btn-chat-send').click(function() {
        console.log();
        sendMessage($(this));
        var to = $(this).closest('.input-group').find('.btn-chat-send').attr("data-id-email");
        scrollToBottom(to);
    });
    $('.chat_input').keypress(function(e) {
        if(e.which == 13) {
            $(this).closest('.input-group').find('.btn-chat-send').click();
        }
    }); 
    $('#userListCategory').find('li').click(function() {
        var type = $(this).attr("data-id");
        $('#userListCategory').attr("data-current-selection", type);            
        loadUserContactList(type);
    });             
    $('.user_list_entry').click(function() {
        var selectedUserEmail = $(this).attr('data-id-email');
        createNewChatBox(selectedUserEmail);
        var id = getChatWindowId(getElementIdSuffix(selectedUserEmail));
        $('#'+id).find('.chat_input').focus();
    });
    $('.chat_input').focus(function() {         
        var to = $(this).closest('.input-group').find('.btn-chat-send').attr("data-id-email");
        var notificationId = getChatUserNotificationId(getElementIdSuffix(to));
        if($('#'+notificationId).text() != '0') {
            markMessagesAsRead(to);
        }
    }); 


};

return {
    initEvent : function() {
        connect();
    }, initAction : function() {
        eventClick();
    }       
}
}();

我不知道为什么我得到这个异常,异常是空指针Exception并且它没有指向我的代码,

我有一个问题,

1- deflator websockets的作用是什么?如果我们面对其中的一些,如何解决?怎么解决?

这是我的ChatEndPoint.java

package com.chat.config;

import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.logging.Logger;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.chat.core.dao.ex.SQLException;
import com.chat.core.repository.MessageRepository;
import com.chat.core.repository.impl.MessageRepositoryImpl;
import com.chat.core.util.Constants;

@ServerEndpoint(value = "/chat/{username}", decoders = MessageDecoder.class, encoders = MessageEncoder.class)
public class ChatEndPoint {

private final Logger log = Logger.getLogger(getClass().getName());

private static MessageRepository messageRespoitory = MessageRepositoryImpl.getInstance();

private Session session;
private String username;
private static final Set<ChatEndPoint> chatEndpoints = new CopyOnWriteArraySet<>();
private static HashMap<String, String> users = new HashMap<>();

@OnOpen
public void onOpen(Session session, @PathParam("username") String username) throws IOException, EncodeException {
    log.info(session.getId() + " connected!");
    this.session = session;
    this.username = username;
    chatEndpoints.add(this);
    users.put(session.getId(), username);
    broadcastRefreshContact();
    System.out.println("Active endpoints count : " +  chatEndpoints.size());
    System.out.println("Active endpoints : " +  chatEndpoints);     
}

@OnMessage
public void onMessage(Session session, Message message) throws IOException, EncodeException {
    log.info(message.toString());
    System.out.println("onMessage : " + message.toString());
    message.setFrom(users.get(session.getId()));
    persistMessage(message);
    sendMessageToOneUser(message);
}

private static void persistMessage(Message message) {
    try {
        messageRespoitory.create(message.getFrom(), message.getTo(), message.getContent());
    } catch (SQLException e) {
        System.out.print("Unable to persist message");
        e.printStackTrace();
    }       
}

@OnClose
public void onClose(Session session) throws IOException, EncodeException {
    log.info(session.getId() + " disconnected!");

    chatEndpoints.remove(this);
    broadcastRefreshContact();      
}

@OnError
public void onError(Session session, Throwable throwable) throws IOException, EncodeException {
    broadcastRefreshContact();
    log.warning(throwable.toString());
}

private static void broadcastRefreshContact() throws IOException, EncodeException {
    Message message = new Message();
    message.setContent(Constants.REFRESH_CONTACT);
    broadcast(message);     
}

private static void broadcast(Message message) throws IOException, EncodeException {
    for (ChatEndPoint endpoint : chatEndpoints) {
        synchronized (endpoint) {
            endpoint.session.getBasicRemote().sendObject(message);
        }
    }
}

private static void sendMessageToOneUser(Message message) throws IOException, EncodeException {
    for (ChatEndPoint endpoint : chatEndpoints) {
        synchronized (endpoint) {
            if (endpoint.session.getId().equals(getSessionId(message.getTo()))) {
                endpoint.session.getBasicRemote().sendObject(message);
            }
        }
    }
}

private static String getSessionId(String to) {
    if (users.containsValue(to)) {
        for (String sessionId : users.keySet()) {
            if (users.get(sessionId).equals(to)) {
                return sessionId;
            }
        }
    }
    return null;
}

public static Set<String> getOnlineUsers() {
    Set<String> users = new TreeSet<String>();
    for(ChatEndPoint enpoint : chatEndpoints) {
        users.add(enpoint.username);
    }
    return users;
}

@Override
public String toString() {
    return "ChatEndPoint [session=" + session + ", username=" + username
            + "]";
}

}

谢谢!

1 个答案:

答案 0 :(得分:0)

我找到了该异常的根本原因,实际上在后端维护了一个缓存。当用户刷新时,没有正确更新。