当前位置: 首页 > news >正文

springboot使用WebSocket

1、、创建springboot项目,勾选Spring web,并导包

  1. 当前springboot选择的是2.6.13版本,jdk1.8
  2. 尽量选2.几的springboot
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!--工具类 --><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.4.1</version>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId>
</dependency>

2、新建一个websocket包,包中新建两个类,代码如下

package com.example.it.springboot.websocket;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
//websocket包需要与启动类同级别
@Configuration
public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();}
}
package com.example.springbootwebsocket.websocket;/*高于springboot3.0的用这个jakarta
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
*/
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;import cn.hutool.json.JSONUtil;import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;/**** 监听websocket地址  /myWs*/
@ServerEndpoint("/myWs")
@Component
@Slf4j
@EnableScheduling
public class WsServerEndpoint {static Map<String, Session> map = new ConcurrentHashMap<String,Session>();//新增一个方法用于主动向客户端发送消息public static void sendMessage(Object message, String userId) {Session session = map.get(userId);if (session != null) {try {session.getBasicRemote().sendText(JSONUtil.toJsonStr(message));System.out.println("【websocket消息】发送消息成功,用户="+userId+",消息内容"+message.toString());} catch (IOException e) {e.printStackTrace();}}}/**** 连接建立时执行的操作* @param session*/@OnOpenpublic void onOpen(Session session){map.put(session.getId(),session);log.info("session.getId()="+session.getId());log.info("session="+session);log.info("websocket is open");}/**** 收到客户端消息执行的操作* @param text*/@OnMessagepublic String OnMessage(String text){log.info("收到了一条信息:  "+text);return "已收到你的信息" ;}/**** 连接关闭时执行的操作* @param session*/@OnClosepublic void OnClose(Session session){map.remove(session.getId());log.info("websocket is close");}/**** 向客户端发送信息*/@Scheduled(fixedRate = 2000)public void sendMsg() throws IOException {for (String key : map.keySet()){//map.get(key).getBasicRemote().sendText("定时发送,你好");}}
}

3、新建一个websocket.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>wsClient</title><script src="https://code.jquery.com/jquery-3.1.1.min.js"></script><style>.btn-group{display: inline-block;}</style>
</head>
<body>
<input type='text' value='ws://localhost:8080/myWs' class="form-control" style='width:390px;display:inline'id='wsaddr' />
<div class="btn-group" ><button type="button" class="btn btn-default" onclick='addsocket();'>连接</button><button type="button" class="btn btn-default" onclick='closesocket();'>断开</button><button type="button" class="btn btn-default" onclick='$("#wsaddr").val("")'>清空</button><button type="button" class="btn btn-default" onclick='restore()'>还原</button>
</div>
<div id="output" style="border:1px solid #ccc;height:365px;overflow: auto;margin: 20px 0;"></div><input type="text" id='message' class="form-control" style='width:810px' placeholder="待发信息" onkeydown="en(event);"><span class="input-group-btn"><button class="btn btn-default" type="button" onclick="doSend();">发送</button></span>
</div><script>/*组织时间*/function formatDate(now) {var year = now.getFullYear();var month = now.getMonth() + 1;var date = now.getDate();var hour = now.getHours();var minute = now.getMinutes();var second = now.getSeconds();return year + "-" + (month = month < 10 ? ("0" + month) : month) + "-" + (date = date < 10 ? ("0" + date) : date) +" " + (hour = hour < 10 ? ("0" + hour) : hour) + ":" + (minute = minute < 10 ? ("0" + minute) : minute) + ":" + (second = second < 10 ? ("0" + second) : second);}var output;var websocket;function init() {output = document.getElementById("output");}/*连接按钮*/function addsocket() {var wsaddr = $("#wsaddr").val();if (wsaddr == '') {alert("请填写websocket的地址");return false;}StartWebSocket(wsaddr);}/*断开按钮*/function closesocket() {websocket.close();}/*还原按钮*/function restore(){$("#wsaddr").val('ws://localhost:8080/myWs');}function en(event) {var evt = evt ? evt : (window.event ? window.event : null);if (evt.keyCode == 13) {doSend()}}/*发送按钮*/function doSend() {var message = $("#message").val();if (message == '') {alert("请先填写发送信息");$("#message").focus();return false;}if (typeof websocket === "undefined") {alert("websocket还没有连接,或者连接失败,请检测");return false;}if (websocket.readyState == 3) {alert("websocket已经关闭,请重新连接");return false;}console.log(websocket);$("#message").val('');writeToScreen('<span style="color:green">你发送的信息&nbsp;' + formatDate(new Date()) + '</span><br/>' + message);websocket.send(message);}/*书写内容*/function StartWebSocket(wsUri) {websocket = new WebSocket(wsUri);websocket.onopen = function(evt) {onOpen(evt)};websocket.onclose = function(evt) {onClose(evt)};websocket.onmessage = function(evt) {onMessage(evt)};websocket.onerror = function(evt) {onError(evt)};}function onOpen(evt) {writeToScreen("<span style='color:red'>连接成功,现在你可以发送信息啦!!!</span>");}function onClose(evt) {writeToScreen("<span style='color:red'>websocket连接已断开!!!</span>");websocket.close();}function onMessage(evt) {writeToScreen('<span style="color:blue">服务端回应&nbsp;' + formatDate(new Date()) + '</span><br/><span class="bubble">' +evt.data + '</span>');}function onError(evt) {writeToScreen('<span style="color: red;">发生错误:</span> ' + evt.data);}function writeToScreen(message) {var div = "<div class='newmessage'>" + message + "</div>";var d = $("#output");var d = d[0];var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;$("#output").append(div);if (doScroll) {d.scrollTop = d.scrollHeight - d.clientHeight;}}</script>
</body>
</html>

4、新建一个后台发送测试类

package com.example.it.springboot.controller;import com.example.it.springboot.websocket.WsServerEndpoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;import java.io.IOException;@Controller
public class TestController {private WsServerEndpoint wsServerEndpoint;//localhost:8080/hello@GetMapping("/hello")public String setHello2() {System.out.println("Hello ???");wsServerEndpoint.sendMessage("我发了一个测试","0");return "Hello";}
}

5、访问websocket.html,进行测试,

参考链接

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • LeetCode257 二叉树的所有路径
  • 高可用集群KEEPALIVED
  • opencv色彩空间类型转换
  • LLM微调(精讲)-以高考选择题生成模型为例(DataWhale AI夏令营)
  • 前端创作纪念日
  • go语言协程之间的同步
  • 第十章、 异常Exception
  • 东土科技车规级网络芯片获批量应用
  • leetcode300. 最长递增子序列,动态规划附状态转移方程
  • Android 让程序随系统自动启动并允许后台运行(白名单)
  • arch linux 安装Budgie桌面
  • MySQL约束
  • 一、软件工程概述
  • 网络协议十 应用层 SPDY / HTTP2 / QUIC / HTTP3
  • 使用mybatis注解和xml映射执行javaWeb中增删改查等操作
  • -------------------- 第二讲-------- 第一节------在此给出链表的基本操作
  • 【干货分享】SpringCloud微服务架构分布式组件如何共享session对象
  • 08.Android之View事件问题
  • es6(二):字符串的扩展
  • MYSQL如何对数据进行自动化升级--以如果某数据表存在并且某字段不存在时则执行更新操作为例...
  • 翻译 | 老司机带你秒懂内存管理 - 第一部(共三部)
  • 将 Measurements 和 Units 应用到物理学
  • 开源地图数据可视化库——mapnik
  • 聊聊hikari连接池的leakDetectionThreshold
  • 为什么要用IPython/Jupyter?
  • 想晋级高级工程师只知道表面是不够的!Git内部原理介绍
  • 如何用纯 CSS 创作一个菱形 loader 动画
  • ​​​​​​​Installing ROS on the Raspberry Pi
  • ​插件化DPI在商用WIFI中的价值
  • ​猴子吃桃问题:每天都吃了前一天剩下的一半多一个。
  • ​字​节​一​面​
  • #13 yum、编译安装与sed命令的使用
  • #快捷键# 大学四年我常用的软件快捷键大全,教你成为电脑高手!!
  • (1)Map集合 (2)异常机制 (3)File类 (4)I/O流
  • (CVPRW,2024)可学习的提示:遥感领域小样本语义分割
  • (超简单)使用vuepress搭建自己的博客并部署到github pages上
  • (二)Linux——Linux常用指令
  • (附源码)springboot助农电商系统 毕业设计 081919
  • (附源码)计算机毕业设计SSM在线影视购票系统
  • (转载)微软数据挖掘算法:Microsoft 时序算法(5)
  • .Net Memory Profiler的使用举例
  • .Net实现SCrypt Hash加密
  • .NET实现之(自动更新)
  • [ vulhub漏洞复现篇 ] Apache Flink目录遍历(CVE-2020-17519)
  • [8] CUDA之向量点乘和矩阵乘法
  • [Algorithm][动态规划][简单多状态DP问题][按摩师][打家劫舍Ⅱ][删除并获得点数][粉刷房子]详细讲解
  • [Android]Android P(9) WIFI学习笔记 - 扫描 (1)
  • [BZOJ 1040] 骑士
  • [CLickhouse] 学习小计
  • [codevs 1288] 埃及分数 [IDdfs 迭代加深搜索 ]
  • [DL]深度学习_Feature Pyramid Network
  • [EFI]MSI GF63 Thin 9SCXR电脑 Hackintosh 黑苹果efi引导文件
  • [HJ73 计算日期到天数转换]
  • [HNCTF 2022 WEEK2]easy_include 文件包含遇上nginx
  • [HTML]Web前端开发技术30(HTML5、CSS3、JavaScript )JavaScript基础——喵喵画网页