SpringBoot整合WebSocket

SpringBoot整合WebSocket

一个前后端分离的项目,后端如何主动向前端发送消息呢? websocket

什么是websocket:https://www.ruanyifeng.com/blog/2017/05/websocket.html

一、导入依赖

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

二、配置类

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

三、服务类

@Component
@Slf4j
@ServerEndpoint("/websocket/{userId}")  // 接口路径 ws://localhost:8081/webSocket/xxx;
public class WebSocket {

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

	// 存放每个用户的连接 CopyOnWriteArraySet是线程安全的set
    private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
    
    // 用来存在线连接数
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();

    // 连接成功时调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value="userId")String userId) {
        try {
            this.session = session;
            webSockets.add(this);
            sessionPool.put(userId, session);
        } catch (Exception e) {
        }
    }

    // 关闭连接时调用
    @OnClose
    public void onClose() {
        try {
            webSockets.remove(this);
        } catch (Exception e) {
        }
    }

    // 收到客户端消息时调用
    @OnMessage
    public void onMessage(String message) {
		...
    }

    // 发生错误时调用
    @OnError
    public void onError(Session session, Throwable error) {
        ...
    }


    // 给所有用户发送消息
    public void sendAllMessage(String message) {
        for(WebSocket webSocket : webSockets) {
            try {
                if(webSocket.session.isOpen()) {
                    webSocket.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 给某个用户发送消息
    public void sendOneMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                ...
            }
        }
    }

    // 给多个用户发送消息
    public void sendMoreMessage(String[] userIds, String message) {
        for(String userId:userIds) {
            Session session = sessionPool.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    ...
                }
            }
        }
    }
}

四、发送消息

@SpringBootTest
public class WebSocketTest {
    @Autowired
    private WebSocket webSocket;
   	
    @Test
    public void test01() {
        webSocket.sendAllMessage("666");
    }
}

五、前端接收

在vue的methods中添加以下方法

initWebSocket: function () { // 建立连接
  // WebSocket与普通的请求所用协议有所不同,ws和http类似,wss和https类似
  var user = localStorage.getItem("user");
  var url = "ws://localhost:8081/websocket/"+user.userId;
  this.websock = new WebSocket(url);
  this.websock.onopen = this.websocketonopen;
  this.websock.send = this.websocketsend;
  this.websock.onerror = this.websocketonerror;
  this.websock.onmessage = this.websocketonmessage;
  this.websock.onclose = this.websocketclose;
},
    
// 连接成功后调用
websocketonopen: function () {
	...
},
    
// 发生错误时调用
websocketonerror: function (e) {
	...
},
    
// 给后端发消息时调用
websocketsend: function (e) {
	...
},
// 接收消息时调用
websocketonmessage: function (e) {
	...
},
    
// 关闭连接时调用
websocketclose: function (e) {
    ...
}

然后在页面加载完成之前,如mounted中初始化websocket:

this.initWebSocket()

并且在关闭页面时调用websocketclose,如在destroyed中添加:

this.websocketclose();
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Spring Boot整合WebSocket,你需要进行以下步骤: 1. 首先,在pom.xml文件中添加WebSocket的相关依赖。可以使用以下两个依赖之一: - 从中提到的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` - 从中提到的依赖: ```xml <!--webSocket--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 创建WebSocket配置类,这个类负责配置WebSocket的相关信息。你可以按照以下方式创建一个配置类[3]: ```java package com.loit.park.common.websocket; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } } ``` 3. 至此,你已经完成了WebSocket整合配置。现在,你可以在你的应用中创建WebSocket的控制器并定义你的WebSocket端点。你可以根据你的需求来实现WebSocket端点的业务逻辑。 这就是Spring Boot整合WebSocket的基本步骤。通过这种方式,你可以在Spring Boot应用中轻松地使用WebSocket进行实时通信。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [springboot整合websocket](https://blog.csdn.net/weixin_45390688/article/details/120448778)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [springboot整合websocket(详解、教程、代码)](https://blog.csdn.net/hjq_ku/article/details/127503180)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值