简体   繁体   中英

NullPointerException in Websockets

I'm implementing Websockets on a Tomcat 7 Server. When the client sends some parameters the server performs some tasks through the Updater class. However I want all the server tasks to be stopped any time the connection is closed. This is my server code:

public class FastServlet {

    private Updater up;
    private Session session;

    public FastServlet() {
    }

    @OnOpen
    public void start(Session session) {
        this.session = session;
    }

    @OnClose
    public void end() {
        up.setActive(false);
    }

    @OnMessage
    public void incoming(String query) {
        \\ some code ...

        up = new Updater(parameters, uploadedFile, session);
        up.update();

    }
}

while the Updater class has this form:

  public class Updater {

    private boolean active;

    public Updater(Map<String, String> parameters, java.io.File uploadedFile, Session session) {
        \\constructor
        this.active = true;
    }

    public void update() {
        while (active) {
            \\ do stuff 
        }
    }

However when I call the server and I force a disconnection I get a NullPointerException at the end() method, as if the "up" variable was null. But I am sure that it is not null since I can verify that the update() method has been partially completed. Any help?

partially completed? You cannot guarantee that.It is possible user disconnects prior to execution of incoming() method. It is always safer to put null checks.

    @OnClose
    public void end() {
        if(up != null){
            up.setActive(false);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM