美文网首页
springboot简易消息通知的实现

springboot简易消息通知的实现

作者: qiuzhenjie | 来源:发表于2020-11-11 17:47 被阅读0次

1.引入websocket依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <scope>provided</scope>
        </dependency>

2.添加配置文件WebSocketConfig.class

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3.实现消息通知类WebSocketServer.class

@Component
@ServerEndpoint(value = "/websocket/{id}")
public class WebSocketServer {
    private static int onlineCount = 0;
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    private static Logger log = LogManager.getLogger(WebSocketServer.class);
    private String id = "";

    /**
     * 连接建立成功调用的方法
     * @param id 用户的标识
     * @param session 会话
     */
    @OnOpen
    public void onOpen(@PathParam(value = "id") String id, Session session) {
        //设置超时时间
        session.setMaxIdleTimeout(3600000);
        this.session = session;
        //接收到发送消息的人员编号
        this.id = id;
        //加入set中
        if (webSocketMap.containsKey(id)){
            webSocketMap.remove(id);
        }
        webSocketMap.put(id, this);
        //在线数加1
        addOnlineCount();
        log.info("用户"+id+"加入!当前在线人数为" + getOnlineCount());

        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从map中删除
        webSocketMap.remove(this.id);
        //在线数减1
        subOnlineCount();
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 会话
     * */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息:" + message);
        //可以自己约定字符串内容,比如 内容|0 表示信息群发,内容|X 表示信息发给id为X的用户
        String sendMessage = message.split("[|]")[0];
        String sendUserId = message.split("[|]")[1];
        try {
            if(sendUserId.equals("0")) {
                sendtoAll(sendMessage);
            }
            else {
                sendMessageTo(sendMessage, sendUserId);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }


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

    public void sendMessageTo(String message,String sendUserId) throws IOException{
        if (webSocketMap.get(sendUserId) != null) {
            if(!id.equals(sendUserId)){
                webSocketMap.get(sendUserId).sendMessage( "用户" + id + "发来消息:" + " <br/> " + message);
            }
            else {
                webSocketMap.get(sendUserId).sendMessage(message);
            }
        } else {
            //如果用户不在线则返回不在线信息给自己
//            sendtoUser("当前用户不在线",id);
        }
    }



    /**
     * 发送信息给所有人
     * @param message
     * @throws IOException
     */
    public void sendtoAll(String message) throws IOException {
        for (String key : webSocketMap.keySet()) {
            try {
                webSocketMap.get(key).sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


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

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

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

4.测试
前端js访问http://localhost:8080/websocket/123

相关文章

网友评论

      本文标题:springboot简易消息通知的实现

      本文链接:https://www.haomeiwen.com/subject/ydpjbktx.html