web socket

package com.web;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
* The @ServerEndpoint annotation is a class-level annotation , its function is mainly to define the current class as a websocket server side,
* the value of the annotation will be used to monitor the terminal access URL address of the user connection, the client can connect to the WebSocket server side through this URL
*/
@ServerEndpoint ("/websocket")
public class WebSocketTest {
    //Static variable used to record the current number of online connections. It should be designed to be thread safe.
    private static int onlineCount = 0;

    //The thread-safe Set of the concurrent package is used to store the MyWebSocket object corresponding to each client. If you want to realize the communication between the server and a single client, you can use Map to store, where the Key can be the user ID
    private static CopyOnWriteArraySet<WebSocketTest> webSocketSet = new CopyOnWriteArraySet<WebSocketTest>();

    //A connection session with a client needs to be used to send data to the client
    private Session session;

    /**
     * The method to be called successfully when the connection is established
     * @param session optional parameter. Session is a connection session with a client, which needs to be used to send data to the client
     */
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this); //
        addOnlineCount in set (     )     .
        _      _      _     _     _ ){         webSocketSet.remove(this); //Remove         subOnlineCount() from set; //Online count minus 1









        System.out.println("A connection is closed! The current number of people online is" + getOnlineCount());
    }

    /**
     * The method called after receiving the client message
     * @param message The message sent by the client
     * @param session Optional parameters
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("Message from client:" + message);
        //Group message
        for(WebSocketTest item: webSocketSet){
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    /**
     * Called when an error occurs
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("Error occurred");
        error.printStackTrace();
    }

    /**
     * This method is different from the above methods. No annotations are used, it is a method to be added according to your own needs.
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketTest.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketTest.onlineCount--;
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326988047&siteId=291194637