0

For creating WebSocket server I have used Java-WebSocket library. It looks like this, and it is working.

But now I wish to upgrade, so server can have only one active client connection.
Is there some kind of option for doing this, or should I check all connections, and close all, non-first active, connections?

I have tried that like this:

@Override
public void onOpen(WebSocket conn, ClientHandshake handshake)
{
    System.out.println("WebSocketServer::onOpen()");

    boolean first = true;
    Collection<WebSocket> con = this.connections();
    synchronized(con) {
        for (WebSocket c : con) {
            if (first && c.isOpen()) {
                first = false;
            } else {
                c.close();
            }
        }
    }
}

But this closes all connections, and kills Websocket server. What am I doing wrong?

Glavić
  • 42,781
  • 13
  • 77
  • 107

1 Answers1

0

Try putting a counter outside the onOpen() method, and initialise it to 0. Then in the onOpen() method, check if the counter is 1. If it is, close the connection conn, otherwise increment the counter.

Kurt Pattyn
  • 2,758
  • 2
  • 30
  • 42
  • No, this will not work, since the problem is a little bigger. If I close all connections in `onOpen()` method (aka: deny all connections), WebSocket server is killed (first it is runned onError, then onClose, then onError again). – Glavić Jan 12 '14 at 21:07
  • Maybe it is because you close a socket that is not open yet? – Kurt Pattyn Jan 12 '14 at 21:09
  • How do I check that? If we find out, how to deny all connections, I will then know how to close specific one, or to close all but specific one... – Glavić Jan 12 '14 at 21:21