前言
公司项目需要用到消息提示,那么WebSocket它来了经过我面向百度的学习,废话不多说直接开干.
后端搭建
一、依赖导入
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-starter-websocket</artifactId> |
| </dependency> |
二、搭建websocket服务
1.WebSocketConfig配置文件
| |
| |
| |
| |
| package top.yangbuyi.service_websocket.config; |
| |
| 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(); |
| } |
| } |
2.WebSocketServer服务
| |
| |
| |
| |
| package top.yangbuyi.service_websocket.server; |
| |
| import org.springframework.stereotype.Component; |
| |
| import javax.websocket.*; |
| import javax.websocket.server.PathParam; |
| import javax.websocket.server.ServerEndpoint; |
| import java.io.IOException; |
| import java.util.Date; |
| import java.util.concurrent.CopyOnWriteArraySet; |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| @ServerEndpoint("/service_websocket/wspoint/{loginName}") |
| @Component |
| public class WebSocketServer { |
| |
| |
| |
| |
| private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>(); |
| |
| |
| |
| |
| private Session session; |
| |
| |
| |
| |
| private String loginName = ""; |
| |
| |
| |
| |
| |
| |
| |
| |
| @OnOpen |
| public void onOpen(Session session, @PathParam("loginName") String loginName) { |
| |
| this.loginName = loginName; |
| |
| this.session = session; |
| webSocketSet.add(this); |
| try { |
| sendMessage("success"); |
| } catch (Exception ex) { |
| ex.printStackTrace(); |
| } |
| } |
| |
| |
| |
| |
| |
| @OnClose |
| public void onClose() { |
| webSocketSet.remove(this); |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| @OnMessage |
| public void onMessage(String message, Session session) { |
| System.out.println("接收到来自[" + message + "]发送的消息" + session); |
| |
| |
| |
| |
| |
| |
| |
| |
| } |
| |
| |
| |
| |
| |
| |
| |
| @OnError |
| public void onError(Session session, Throwable error) { |
| error.printStackTrace(); |
| } |
| |
| |
| |
| |
| |
| |
| public void sendMessage(String message) { |
| try { |
| if (this.session != null) { |
| this.session.getBasicRemote().sendText(message); |
| } |
| } catch (IOException e) { |
| e.printStackTrace(); |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| public static void sendInfo(String userName, String msgStr) { |
| for (WebSocketServer item : webSocketSet) { |
| if (item.loginName.equals(userName)) { |
| item.sendMessage(msgStr); |
| } |
| } |
| } |
| } |
| |
自己写个controller
进行调用测试服务端消息发送
| |
| |
| |
| @GetMapping("/sendMessage") |
| public String sendMessage(String userName) { |
| |
| WebSocketServer.sendInfo("这里是服务端发送的消息", userName); |
| return "yes"; |
| } |
| |
| |
| |
前端搭建
一、index.vue
| <!--============================================================================ |
| = - Yang Buyi Copyright (c) 2021 https: |
| ===========================================================================--> |
| |
| <template> |
| <div class="webSocket"> |
| <button id="send" class="btn btn-default" @click="sendMsg('发送杨不易https://yangbuyi.top')">Send</button> |
| <div v-for="item in msgData" :key="item"> |
| {{ item }} |
| </div> |
| </div> |
| </template> |
| <script> |
| |
| export default { |
| name: 'WebSocket', |
| data() { |
| return { |
| |
| msgData: [], |
| websocket: null |
| } |
| }, |
| mounted() { |
| this.connection() |
| |
| }, |
| destroyed() { |
| if (this.websocket != null) this.websocket.close() |
| }, |
| methods: { |
| initWebSocket() { |
| this.connection() |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| }, |
| |
| |
| |
| |
| connection() { |
| const socketUrl = 'ws://localhost:你服务的端口/service_websocket/wspoint/' + '唯一名称' |
| if (typeof (WebSocket) === 'undefined') { |
| console.log('您的浏览器不支持WebSocket') |
| this.$message.error('您的浏览器不支持WebSocket,无法使用推送功能!') |
| } else { |
| this.websocket = new WebSocket(socketUrl) |
| console.log(this.websocket) |
| this.websocket.onopen = this.websocketOnopen |
| this.websocket.onmessage = this.websocketOnmessage |
| this.websocket.onerror = this.websocketOnerror |
| this.websocket.onclose = this.websocketClose |
| } |
| }, |
| websocketOnopen() { |
| this.sendMsg('连接成功第一次https://yangbuyi.top') |
| console.log('连接成功') |
| }, |
| websocketOnerror() { |
| console.log('连接失败') |
| }, |
| websocketClose() { |
| console.log('断开连接') |
| }, |
| websocketOnmessage(data) { |
| |
| this.msgData.push(data) |
| }, |
| sendMsg(val) { |
| this.websocket.send(val) |
| } |
| } |
| } |
| </script> |
| |
测试调用创建的controller 向前端发送消息
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南