• SpringBoot 整合 Websocket 通信demo (附浏览器聊天窗口)


    【男性深夜解压神器】


    https://item.taobao.com/item.htm?spm=a21dvs.23580594.0.0.1d293d0dZgIXMJ&ft=t&id=742087626933

    1. 依赖

    1. <!-- SpringBoot WebSocket -->
    2. <dependency>
    3. <groupId>org.springframework.boot</groupId>
    4. <artifactId>spring-boot-starter-websocket</artifactId>
    5. </dependency>

    2. 自动注册配置类
    1. import org.springframework.context.annotation.Bean;
    2. import org.springframework.context.annotation.Configuration;
    3. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
    4. @Configuration
    5. public class WebSocketConfig {
    6. /**
    7. * ServerEndpointExporter 作用
    8. *
    9. * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
    10. *
    11. * @return
    12. */
    13. @Bean
    14. public ServerEndpointExporter serverEndpointExporter() {
    15. return new ServerEndpointExporter();
    16. }
    17. }

     
    
    3. WebSocket服务类
    

    1. import org.springframework.stereotype.Component;
    2. import javax.websocket.*;
    3. import javax.websocket.server.PathParam;
    4. import javax.websocket.server.ServerEndpoint;
    5. import java.io.IOException;
    6. import java.util.concurrent.CopyOnWriteArraySet;
    7. /**
    8. * postman访问: ws://localhost:8080/ws/{userId}
    9. * 浏览器访问: http://localhost:8080/ws
    10. */
    11. @Component
    12. @ServerEndpoint("/ws/{userId}")
    13. public class WebSocketServer {
    14. private static int onlineCount = 0;
    15. private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    16. private Session session;
    17. private String userId = "";
    18. @OnOpen
    19. public void onOpen(Session session, @PathParam("userId") String userId) {
    20. this.session = session;
    21. webSocketSet.add(this); //加入set中
    22. addOnlineCount(); //在线数加1
    23. this.userId = userId;
    24. sendMessage(userId + "用户" + ", 连接成功 !");
    25. System.out.println("【websocket】 " + userId + "用户" + "已连接!当前在线人数为" + getOnlineCount());
    26. }
    27. @OnClose
    28. public void onClose() {
    29. webSocketSet.remove(this); //从set中删除
    30. subOnlineCount(); //在线数减1
    31. System.out.println("【websocket】 " + userId + "用户" + "已关闭!当前在线人数为" + getOnlineCount());
    32. }
    33. @OnMessage
    34. public void onMessage(String message, Session session) {
    35. if(message.startsWith("target-")){
    36. int index = message.indexOf(":");
    37. String userId = message.substring(7,index);
    38. sendInfo(message.substring(index + 1), userId);
    39. return;
    40. }
    41. this.session = session;
    42. sendMessage("【websocket】 服务端收到来自窗口" + userId + "发送的消息:" + message);
    43. }
    44. @OnError
    45. public void onError(Session session, Throwable error) {
    46. this.session = session;
    47. error.printStackTrace();
    48. }
    49. private void sendMessage(String message) {
    50. try {
    51. this.session.getBasicRemote().sendText(message);
    52. } catch (IOException e) {
    53. e.printStackTrace();
    54. }
    55. }
    56. // 群发消息
    57. /**
    58. * 群发自定义消息
    59. */
    60. public static void sendInfo(String message, @PathParam("userId") String userId) {
    61. System.out.println("【websocket】 推送消息给" + userId + "用户" + ",推送内容:" + message);
    62. for (WebSocketServer item : webSocketSet) {
    63. //这里可以设定只推送给这个userId的,为null则全部推送
    64. if (userId == null) {
    65. // item.sendMessage(message);
    66. } else if (item.userId.equals(userId)) {
    67. item.sendMessage(message);
    68. }
    69. }
    70. }
    71. public static synchronized int getOnlineCount() {
    72. return onlineCount;
    73. }
    74. public static synchronized void addOnlineCount() {
    75. WebSocketServer.onlineCount++;
    76. }
    77. public static synchronized void subOnlineCount() {
    78. WebSocketServer.onlineCount--;
    79. }
    80. public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
    81. return webSocketSet;
    82. }
    83. }

    4. 模拟通信

    1. 【websocket】 2015用户已连接!当前在线人数为1
    2. 【websocket】 7349用户已连接!当前在线人数为2
    3. 【websocket】 推送消息给7349用户,推送内容:你好, 我是2015用户, 很高兴认识你 !
    4. 【websocket】 推送消息给2015用户,推送内容:你好, 我是7349用户, 我也很高兴认识你 !

    1. 访问:http://localhost:8080/ws
    2. 可以打开多个
    3. 开始连接,一个客户端给另一个客户端发消息。
    4. 可以服务端推送消息给所有连接的客户端
    5. POST:http://localhost:8080/push
    6. 任意内容

    5. 需要完整代码的可私信我
  • 相关阅读:
    如何保护压缩包里的内容不被看到?
    终端仿真软件连接交换机调试步骤
    虚拟内存的实现与特征
    ASEMI快恢复二极管ES5JB参数,ES5JB特性,ES5JB机械数据
    GBase 8a MPP集群VC管理之操作VC
    基于Rabbitmq和Redis的延迟消息实现
    2023/9/8 -- C++/QT
    Gitlab SSRF 漏洞复现 CVE-2021-22214
    物联网毕业设计 - 基于单片机的静脉输液流速流量监测系统
    mybatis的SqlSession
  • 原文地址:https://blog.csdn.net/weixin_43652507/article/details/132768454