SpringBoot整合WebSocket【代码】

本文详细介绍了如何在SpringBoot项目中集成WebSocket功能,包括依赖引入、WebSocketConfig配置、SessionWrap类的自定义和WebSocketServer的实现,提供了代码示例和错误处理机制。
摘要由CSDN通过智能技术生成

系列文章目录

一、SpringBoot连接MySQL数据库实例【tk.mybatis连接mysql数据库】
二、SpringBoot连接Redis与Redisson【代码】
三、SpringBoot整合WebSocket【代码】
四、SpringBoot整合ElasticEearch【代码示例】



代码下载地址

SpringBoot整合WebSocket【代码】


一、效果演示

测试链接
在这里插入图片描述

在这里插入图片描述

二、引入依赖

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

三、WebSocketConfig

@Configuration
public class WebSocketConfig {

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

四、SessionWrap

SessionWrap 可根据具体需求自定义

@Data
public class SessionWrap {

    private String from;	// 连接Id

    private String type;	// 来凝结类型

    private Session session;

    private Date lastTime;
}

五、WebSocketServer

@Slf4j
@Component
@ServerEndpoint(value = "/api/websocket/{from}/{type}")
public class WebSocketServer {

    @Autowired
    private MessageService messageService;

    public static WebSocketServer webSocketServer;

    // 所有的连接会话
    private static CopyOnWriteArraySet<SessionWrap> sessionList = new CopyOnWriteArraySet<>();

    private String from;
    private String type;

    @PostConstruct
    public void init() {
        webSocketServer = this;
        webSocketServer.messageService = this.messageService;
    }

    /**
     * @author Lee
     * @date 2023/7/18 13:57
     * @description 创建连接
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "from") String from, @PathParam(value = "type") String type) {
        this.from = from;
        this.type = type;
        try {
            // 遍历list,如果有会话,更新,如果没有,创建一个新的
            for (SessionWrap item : sessionList) {
                if (item.getFrom().equals(from) && item.getType().equals(type)) {
                    item.setSession(session);
                    item.setLastTime(new Date());
                    log.info("【websocket消息】更新连接,总数为:" + sessionList.size());
                    return;
                }
            }
            SessionWrap sessionWrap = new SessionWrap();
            sessionWrap.setFrom(from);
            sessionWrap.setType(type);
            sessionWrap.setSession(session);
            sessionWrap.setLastTime(new Date());
            sessionList.add(sessionWrap);
            log.info("【websocket消息】有新的连接,总数为:" + sessionList.size());
        } catch (Exception e) {
            log.info("【websocket消息】连接失败!错误信息:" + e.getMessage());
        }
    }

    /**
     * @author Lee
     * @date 2023/7/18 13:57
     * @description 关闭连接
     */
    @OnClose
    public void onClose() {
        try {
            sessionList.removeIf(item -> item.getFrom().equals(from) && item.getType().equals(type));
            log.info("【websocket消息】连接断开,总数为:" + sessionList.size());
        } catch (Exception e) {
            log.info("【websocket消息】连接断开失败!错误信息:" + e.getMessage());
        }
    }

    /**
     * @author Lee
     * @date 2023/7/18 14:04
     * @description 发送消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
        	// 对消息进行处理
            JSONObject r = webSocketServer.messageService.insertMessage(message);
            String userId = r.getString("userId");
            for (SessionWrap item : sessionList) {
            // 发送消息的判断逻辑可根据需求修改
                if (item.getFrom().equals(userId) && item.getType().equals("test")) {
                    item.getSession().getBasicRemote().sendText(r.toJSONString());
                    log.info("【websocket消息】发送消息成功:" + r.toJSONString());
                }
            }
        } catch (Exception e) {
            log.info("【websocket消息】发送消息失败!错误信息:" + e.getMessage());
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {

        log.error("用户错误,原因:"+error.getMessage());
        error.printStackTrace();
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单的Spring Boot应用程序,它使用WebSocket进行通信: 1. 添加依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 创建WebSocket配置类 创建一个WebSocket配置类,用于配置WebSocket: ``` @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new MyWebSocketHandler(), "/my-websocket"); } } ``` 在这个配置类中,我们注册了一个WebSocket处理程序(MyWebSocketHandler),并将其映射到“/my-websocket”端点上。 3. 创建WebSocket处理程序 创建一个WebSocket处理程序,用于处理WebSocket请求: ``` public class MyWebSocketHandler extends TextWebSocketHandler { private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { for (WebSocketSession s : sessions) { s.sendMessage(new TextMessage("Received message: " + message.getPayload())); } } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); } } ``` 在这个处理程序中,我们创建了一个会话列表,用于存储所有连接到WebSocket的会话。当一个新的WebSocket会话建立时,我们将其添加到会话列表中。当我们收到一个消息时,我们遍历会话列表,并将消息发送回每个会话。当WebSocket会话关闭时,我们从会话列表中删除该会话。 4. 创建WebSocket客户端 创建一个WebSocket客户端,用于连接到WebSocket服务器并发送消息: ``` public class MyWebSocketClient extends WebSocketClient { public MyWebSocketClient(URI serverUri, Draft draft) { super(serverUri, draft); } @Override public void onOpen(ServerHandshake handshakedata) { send("Hello, server!"); } @Override public void onMessage(String message) { System.out.println("Received message: " + message); } @Override public void onClose(int code, String reason, boolean remote) { System.out.println("WebSocket closed"); } @Override public void onError(Exception ex) { System.out.println("WebSocket error"); } } ``` 在这个WebSocket客户端中,我们定义了一些回调方法,用于处理WebSocket事件。当WebSocket连接建立时,我们发送一条消息。当我们收到一条消息时,我们将其打印到控制台上。当WebSocket连接关闭时,我们打印一条消息。当WebSocket发生错误时,我们打印一条消息。 5. 启动WebSocket服务器 最后,我们在Spring Boot应用程序的main方法中启动WebSocket服务器: ``` @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); WebSocketServerFactory factory = new DefaultWebSocketServerFactory(); WebSocketServer server = factory.createWebSocketServer(); server.start(); } } ``` 在这个main方法中,我们启动了Spring Boot应用程序,并创建了一个WebSocket服务器。我们使用默认的WebSocket服务器工厂来创建WebSocket服务器。我们调用start方法来启动WebSocket服务器。 现在,我们就完成了Spring Boot应用程序和WebSocket服务器的配置。运行应用程序,并使用WebSocket客户端连接到WebSocket服务器。您应该能够发送和接收消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李子木、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值