简体   繁体   中英

How to restrict WebSocket server connection to only one?

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?

尝试将计数器放在onOpen()方法外部,并将其初始化为0。然后在onOpen()方法中,检查计数器是否为1。如果是,请关闭连接conn ,否则增加计数器。

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