zoukankan      html  css  js  c++  java
  • 个人博客

    2021年5月18日:

    今天完善了最基本的websocket代码,现在已经可以实现团员发送申请,然后社长得到请求:

    package com.atguigu.crud.utils;

    import javax.websocket.*;
    import javax.websocket.server.PathParam;
    import javax.websocket.server.ServerEndpoint;
    import org.springframework.stereotype.Component;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;

    @ServerEndpoint("/websocket/{userno}")
    @Component
    public class websocket {
    private static ConcurrentHashMap<String, websocket> webSocketSet = new ConcurrentHashMap<String, websocket>();
    private Session WebSocketsession;
    private String userno = "";

    @OnOpen
    public void onOpen(@PathParam(value = "userno") String param, Session WebSocketsession, EndpointConfig config)
    throws IOException {
    userno = param;
    this.WebSocketsession = WebSocketsession;
    websocket webSocketServer = webSocketSet.get(param);
    if (webSocketServer != null) { // 同样业务的连接已经在线,则把原来的挤下线。
    webSocketServer.WebSocketsession.getBasicRemote().sendText(param + "重复连接被挤下线了");
    webSocketServer.WebSocketsession.close();
    }
    webSocketSet.put(param, this);
    }

    @OnClose
    public void onClose() {
    if (!userno.equals("")) {
    webSocketSet.remove(userno);
    }
    }

    @OnMessage
    public void onMessage(String message) {
    if (message.split("[|]")[1].contains(",")) {
    sendAll(message.split("[|]")[1].split(","));
    } else {
    sendToUser(message);
    }
    }
    public void sendToUser(String message) {
    String sendUserno = message.split("[|]")[1];
    String sendMessage = message.split("[|]")[0];
    try {
    if (webSocketSet.get(sendUserno) != null) {
    webSocketSet.get(sendUserno).sendMessage(sendUserno);
    }
    } catch (IOException e) {
    }
    }

    private void sendAll(String a[]) {
    for (String key : a) {
    try {
    if (webSocketSet.get(key) != null) {
    webSocketSet.get(key).sendMessage(key);
    }
    } catch (IOException e) {
    }
    }
    }

    @OnError
    public void onError(Session session, Throwable error) {
    error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
    this.WebSocketsession.getBasicRemote().sendText(message);
    }
    }

    这段后端的代码的意思在于当用户发起入团申请之后,界面就会发起一条信息传到websocket的服务器,当用户登录时就会连接到服务器然后就会发送一条信息给社长,但是现在有一个问题那就是如果社长没在线那就发不了,这个问题是我在做的过程中发现的,所以现在我要一种方法来解决如果别人断线的问题。

  • 相关阅读:
    (转)Openldap相关精品文章
    (转)一条SQL更新语句是如何执行的
    Mysql5.7不区分大小写设置
    为什么Kafka那么快,明显领先其他mq?
    Linux误挂载到根目录出现问题!!!!!!!!!!!!!!!
    什么是跨域?解决跨域的六种方法。
    Nginx常用rewrite跳转重定向实例
    Python概念-禁锢术之__slots__
    Python概念-Item系列(林海峰教的)
    Python练习-基于授权方式包装list之与根儿哥必有一战
  • 原文地址:https://www.cnblogs.com/yitiaokuailedexiaojingyu/p/14872902.html
Copyright © 2011-2022 走看看