Java使用websocket实现消息实时通知

前言

博客仅做学习记录使用。
做项目中遇到这样一个实时通知需求,因为第一次接触这个,期间查了很多资料,看了很多博客,最后实现功能,查询的博客太多,就不一一放出来了,感谢各位大佬。
websocket方式主要代码来源于这个大佬的博客:
https://blog.csdn.net/moshowgame/article/details/80275084

1. 集成依赖

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

2.websocket配置文件

这个配置文件可以理解为开启对websocket支持

@Configuration
public class WebsocketConfig {

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

这个配置文件就是对连接进行一些相关的操作,和发送消息。
这里解释一下这几个注解的作用:

@ServerEndpoint(“/websocket/{userId}”),标记websocket的服务端连接url,前端通过该url建立连接;
@OnOpen,连接成功时执行的方法;
@OnClose,连接关闭时执行的方法;
@OnError,连接发生错误执行的方法;
@OnMessage,服务端接收客户端消息时执行的业务处理。比如代码这里,接收到客户端发送的消息时,在这个方法中,服务端将消息发送给对应的客户端。

@Component
@Slf4j
@ServerEndpoint("/websocket/{userId}")  // 接口路径 ws://localhost:9000/webSocket/userId;
public class WebsocketServer {
    /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,WebsocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if(webSocketMap.containsKey(userId)){
            webSocketMap.put(userId,this);
            //加入set中
        }else{
            webSocketMap.put(userId,this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }
        log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("用户:"+userId+",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String jsonMessage, Session session) {
        log.info("用户消息:{} ,jsonMessage -> {}", userId, jsonMessage);
        // 消息持久化 TODO
        if (StringUtils.isNotBlank(jsonMessage)) {
            MessageVo messageVo = JSONUtil.toBean(jsonMessage, MessageVo.class);
            messageVo.setUserId(this.userId); // 增加发送人,防止篡改
            String toUserId = messageVo.getToUserId();
            if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
                try {
                    webSocketMap.get(toUserId).sendMessage(messageVo.getContent());
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("消息发送错误");
                }
            } else {
                log.info("接收者userId: {}, 当前不在线", toUserId);
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 发送自定义消息
     *
     */
    public static boolean sendInfo(String message,@PathParam("userId") String userId) throws IOException {
        log.info("发送消息到:" + userId + ",报文:" + message);
        if(StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage(message);
            return true;
        }else{
            log.error("用户" + userId + ",不在线!");
            return false;
        }
    }

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

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

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

MessageVo可以根据实际业务需求修改,我这里的MessageVo如下:

@Data
@ApiModel("客户端消息发送vo")
public class MessageVo {

    @ApiModelProperty("发送者id")
    private String userId;

    @ApiModelProperty("接收者")
    private String toUserId;

    @ApiModelProperty("消息内容")
    private String content;
}

校验连接是否成功 html:

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Test</title>
    <script>
        var webSocket = new WebSocket("ws://localhost:9000/websocket/1234");
		
        webSocket.onopen = function (event) {
            console.log("WebSocket opened.");
        };

        webSocket.onmessage = function (event) {
            console.log("Received message: " + event.data);
        };

        webSocket.onclose = function (event) {
            console.log("WebSocket closed.");
        };

        function sendMessage() {
            var message = document.getElementById("message").value;
            webSocket.send(message);
        }
    </script>
</head>
<body>
    <input type="text" id="message" placeholder="Enter message">
    <button onclick="sendMessage()">Send</button>
</body>
</html>

在html中,将下面代码中的url替换成自己websocket中的服务端url查看浏览器控制台就可以看到是否建立连接成功。

var webSocket = new WebSocket("ws://localhost:9000/websocket/1234");

这里注意如果yml配置文件中配置了context-path,要在url中加上对应的path,我这里没配,不需要加。

server:
  port: 9000
  servlet:
    context-path: /

3.集成中遇到的问题

(1)建立连接时日志报 no mapping for GET xxx

这里检查一下是否没有配置开启websocket支持,开启方式见前面。

(2)启动项目报错 javax.websocket.server.ServerContainer not available

我这里写demo的时候遇到这个问题了,集成到工作项目中没遇到。
这的解决方式是排除spring-boot-starter-web中的内嵌tomcat,如下:

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
     <!-- 兼容websocket -->
     <exclusions>
         <exclusion>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-tomcat</artifactId>
         </exclusion>
     </exclusions>
 </dependency>

4.其他方案

在我刚开始接触查资料的时候,我发现很多人给的写法都不一样,后来我才知道除了我现在这种方案,另一种是stomp协议方式,通过配置文件订阅端点(我个人认为类似前面的@ServerEndpoint作用,但是我没去验证)
通过SimpMessageTemplate中的方法向指定端点发送消息,其中使用最多的是:
convertAndSend(String destination, Object payload),向指定地址(端点)发送消息;
convertAndSendToUser(String user, String destination, Object payload),向指定用户,地址(端点)发送消息。

这里贴出学习过程中贴出代码:

WebConfig:

@Configuration
@EnableWebSocket // 开启spring对websocket的支持
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private MyWebSocketHandler webSocketHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(webSocketHandler, "/websocket") // 设置端点
                .setAllowedOrigins("*") // 设置允许跨域
                .withSockJS();
    }

    @Bean
    public SimpMessagingTemplate simpMessagingTemplate() {
        return new SimpMessagingTemplate((message, timeout) -> false);
    }
}

MyWebSocketHandler :

@Component
@Slf4j
public class MyWebSocketHandler implements WebSocketHandler {

    @Override // 对应@OnOpen
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 连接建立后执行的操作
        log.info("websocket连接建立成功");
    }

    @Override // 对应@OnMessage
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        // 处理消息
        // ...
        // 发送消息
    }

    @Override // 对应@OnError
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 处理传输错误
        log.info("websocket处理错误");
    }

    @Override // 对应@OnClose
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        log.info("websocket连接关闭");
    }

	// 是否支持部分消息
	// false表示不支持,当一个完整的消息无法一次性被传输时,WebSocket 连接会将其存储下来,直到所有的数据都被接收完成并组装成完整的消息后再进行处理。
	// true表示支持,当一个完整的消息无法一次性被传输时,WebSocket 连接会自动将其拆分成更小的部分进行发送,并在接收方重新组装成完整的消息。
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}

我最开始选用的这种方案,但是使用前面的html一直提示连接失败,后来查阅资料后发现这种方式对应的前端代码也得改一下,部分代码如下:

<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
<script type="text/javascript">
	var socket = new SockJS("http://localhost:9000/websocket");
	var stompClient = Stomp.over(socket);
</script>

因为功能催得急,所以之前选用这个不行的时候就马上改成第一种方式了,这个也没来得及测试是否可以,如果遇到上面提到的问题可以尝试使用相同方法解决一下,如果文章有错误欢迎各位大佬指出。

  • 2
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值