There’s nothing to talk about. Can we just get to the code

  • Message management tools in Flutter:
class MessageUtils {
  static WebSocket _webSocket;
  static num _id = 0;

  static void connect() {
    Future<WebSocket> futureWebSocket =
        WebSocket.connect(Api.WS_URL + "/leyan");WS_URL is the websocket service on the server side
    futureWebSocket.then((WebSocket ws) {
      _webSocket = ws;
      _webSocket.readyState;
      // Listen on events
      void onData(dynamic content) {
        _id++;
        _sendMessage("Receive");
        _createNotification("New news", content + _id.toString());
      }

      _webSocket.listen(onData,
          onError: (a) => print("error"), onDone: () => print("done"));
    });
  }

  static void closeSocket() {
    _webSocket.close();
  }

  // Send a message to the server
  static void _sendMessage(String message) {
    _webSocket.add(message);
  }

  // Mobile phone status bar pops up push message
  static void _createNotification(String title, String content) async {
    await LocalNotifications.createNotification(
      id: _id,
      title: title,
      content: content,
      onNotificationClick: NotificationAction(
          actionText: "some action",
          callback: _onNotificationClick,
          payload: "Received successfully!")); }static _onNotificationClick(String payload) {
    LocalNotifications.removeNotification(_id);
    _sendMessage("Message has been read"); }}Copy the code
  • Websocket services:
@ServerEndpoint(value = "/api/ws/{userid}")/ / the corresponding Api. WS_URL
@Component
public class SocketServer {

    private Session session;
    private static Map<String, Session> sessionPool = new HashMap<>();
    private static Map<String, String> sessionIds = new HashMap<>();

    private static Map<String, TreeSet<String>> remainingMessagePool = new HashMap<>(128);

    /** ** triggers ** when the user connects@param session
     * @param userid
     */
    @OnOpen
    public void open(Session session, @PathParam(value = "userid") String userid) {
        this.session = session;
        sessionPool.put(userid, session);
        sessionIds.put(session.getId(), userid);
        // Offline message sending
        if(remainingMessagePool.get(userid) ! =null) { TreeSet<String> remainingMessages = remainingMessagePool.get(userid); remainingMessages.forEach(it -> sendMessage(it, userid)); remainingMessagePool.remove(userid); }}/** ** Is triggered when a message is received@param message
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("Sender :" + sessionIds.get(session.getId()) + Content: "" + message);
    }

    /** * Connection closure trigger */
    @OnClose
    public void onClose(a) {
        sessionPool.remove(sessionIds.get(session.getId()));
        sessionIds.remove(session.getId());
    }

    /** ** is triggered when an error occurs@param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /** * How to send messages **@param message
     * @param userId
     */
    public static void sendMessage(String message, String userId) {
        Session s = sessionPool.get(userId);
        if(s ! =null) {
            try {
                s.getBasicRemote().sendText(message);
            } catch(IOException e) { e.printStackTrace(); }}else {
            // Offline message store
            if(remainingMessagePool.get(userId) ! =null) {
                TreeSet<String> remainingMessages = remainingMessagePool.get(userId);
                remainingMessages.add(message);
            } else {
                TreeSet<String> remainingMessages = newTreeSet<>(); remainingMessages.add(message); remainingMessagePool.put(userId, remainingMessages); }}}/** * get the current connection number **@return* /
    public static int getOnlineNum(a) {
        return sessionPool.size();
    }

    /** * get online user names separated by commas **@return* /
    public static String getOnlineUsers(a) {
        StringBuffer users = new StringBuffer();
        for (String key : sessionIds.keySet()) {
            users.append(sessionIds.get(key) + ",");
        }
        return users.toString();
    }

    /** * message group **@param msg
     */
    public static void sendAll(String msg) {
        for(String key : sessionIds.keySet()) { sendMessage(msg, sessionIds.get(key)); }}/** * multiple people send to several specified users **@param msg
     * @paramPersons */

    public static void SendMany(String msg, String[] persons) {
        for(String userid : persons) { sendMessage(msg, userid); }}}Copy the code