Spring boot使用websocket实现在线聊天

embedded/2024/10/18 22:19:45/

maven依赖

		<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.26</version></dependency>

Java 类

WebSocket 配置

package com.zpjiang.chat;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;@Configuration
public class WebSocketConfig {/*** 	注入ServerEndpointExporter,* 	这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint*/@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}

websocketuserId_50">WebSocket 接口入径(ws://localhost:8087/socket/websocket/userId)

package com.zpjiang.chat;import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;import org.springframework.stereotype.Component;import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;@Component
@Slf4j
@ServerEndpoint("/websocket/{userId}") // 接口路径  ws://localhost:8087/socket/websocket/userId;
public class WebSocket {// 与某个客户端的连接会话,需要通过它来给客户端发送数据private Session session;/*** 用户ID*/private String userId;// concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。// 虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。// 注:底下WebSocket是当前类名private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();// 用来存在线连接用户信息private static ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<String, Session>();/*** 链接成功调用的方法*/@OnOpenpublic void onOpen(Session session, @PathParam(value = "userId") String userId) {try {this.session = session;this.userId = userId;webSockets.add(this);sessionPool.put(userId, session);log.info("【websocket消息】有新的连接,总数为:" + webSockets.size());} catch (Exception e) {}}/*** 链接关闭调用的方法*/@OnClosepublic void onClose() {try {webSockets.remove(this);sessionPool.remove(this.userId);log.info("【websocket消息】连接断开,总数为:" + webSockets.size());} catch (Exception e) {}}/*** 收到客户端消息后调用的方法** @param message* @param session*/@OnMessagepublic void onMessage(String message) {log.info("【websocket消息】收到客户端消息:" + message);Message msg = JSONUtil.toBean(message, Message.class);sendOneMessage(msg.getToUID(), message);}/*** 发送错误时的处理* * @param session* @param error*/@OnErrorpublic void onError(Session session, Throwable error) {log.error("用户错误,原因:" + error.getMessage());error.printStackTrace();}// 此为广播消息public void sendAllMessage(String message) {log.info("【websocket消息】广播消息:" + 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 {log.info("【websocket消息】 单点消息:" + message);session.getAsyncRemote().sendText(message);} catch (Exception e) {e.printStackTrace();}}}// 此为单点消息(多人)public void sendMoreMessage(String[] userIds, String message) {for (String userId : userIds) {Session session = sessionPool.get(userId);if (session != null && session.isOpen()) {try {log.info("【websocket消息】 单点消息:" + message);session.getAsyncRemote().sendText(message);} catch (Exception e) {e.printStackTrace();}}}}}

controller

package com.zpjiang.chat;import javax.annotation.Resource;import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;@RestController
public class WebsocketController {@Resourceprivate WebSocket webSocket;@GetMapping("/page")public ModelAndView page() {return new ModelAndView("webSocket");}@RequestMapping("/push/{toUID}/{msg}")public ResponseEntity<String> pushToClient(@PathVariable("msg")String message, @PathVariable("toUID") String toUID) throws Exception {webSocket.sendOneMessage(toUID, message);return ResponseEntity.ok("Send Success!");}
}

消息bean

package com.zpjiang.chat;import lombok.Data;
import lombok.Getter;
import lombok.Setter;@Data
@Getter
@Setter
public class Message {private String toUID;private String Msg;
}

main方法类

package com.zpjiang.chat;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class ChatApplication {public static void main(String[] args) {SpringApplication.run(ChatApplication.class, args);}
}

配置文件

server:port: 8087servlet:context-path: /socketspring:application:name: websocket

视图文件 /src/main/resources/templates/webSocket.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebSocket消息通知</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>var socket;//打开WebSocketfunction openSocket() {if (typeof (WebSocket) === "undefined") {console.log("您的浏览器不支持WebSocket");} else {console.log("您的浏览器支持WebSocket");//实现化WebSocket对象,指定要连接的服务器地址与端口,建立连接.//ws://localhost:8087/socket/websocket/userIdvar socketUrl = "http://localhost:8087/socket/websocket/"+ $("#uid").val();//将https与http协议替换为ws协议socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");console.log(socketUrl);if (socket != null) {socket.close();socket = null;}socket = new WebSocket(socketUrl);//打开事件socket.onopen = function() {console.log("WebSocket已打开");//socket.send("这是来自客户端的消息" + location.href + new Date());};//获得消息事件socket.onmessage = function(msg) {console.log(msg.data);//发现消息进入,开始处理前端触发逻辑};//关闭事件socket.onclose = function() {console.log("WebSocket已关闭");};//发生了错误事件socket.onerror = function() {console.log("WebSocket发生了错误");}}}var socket1;//打开WebSocketfunction openSocket1() {if (typeof (WebSocket) === "undefined") {console.log("您的浏览器不支持WebSocket");} else {console.log("您的浏览器支持WebSocket");//实现化WebSocket对象,指定要连接的服务器地址与端口,建立连接.//ws://localhost:8087/socket/websocket/userIdvar socketUrl = "http://localhost:8087/socket/websocket/"+ $("#toUID").val();//将https与http协议替换为ws协议socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");console.log(socketUrl);if (socket1 != null) {socket1.close();socket1 = null;}socket1 = new WebSocket(socketUrl);//打开事件socket1.onopen = function() {console.log("WebSocket已打开");//socket.send("这是来自客户端的消息" + location.href + new Date());};//获得消息事件socket1.onmessage = function(msg) {console.log("socket1收到消息:");console.log(msg.data);//发现消息进入,开始处理前端触发逻辑};//关闭事件socket1.onclose = function() {console.log("WebSocket已关闭");};//发生了错误事件socket1.onerror = function() {console.log("WebSocket发生了错误");}}}//发送消息function sendMessage() {if (typeof (WebSocket) === "undefined") {console.log("您的浏览器不支持WebSocket");} else {console.log("您的浏览器支持WebSocket");console.log('{"toUID":"' + $("#toUID").val() + '","Msg":"'+ $("#msg").val() + '"}');socket.send('{"toUID":"' + $("#toUID").val() + '","Msg":"'+ $("#msg").val() + '"}');}}function sendMessage1() {if (typeof (WebSocket) === "undefined") {console.log("您的浏览器不支持WebSocket");} else {console.log("您的浏览器支持WebSocket");console.log('{"toUID":"' + $("#uid").val() + '","Msg":"'+ $("#msg").val() + '"}');socket1.send('{"toUID":"' + $("#uid").val() + '","Msg":"'+ $("#msg").val() + '"}');}}
</script>
<body><p>【uid】:<div><input id="uid" name="uid" type="text" value="1"></div><p>【toUID】:<div><input id="toUID" name="toUID" type="text" value="2"></div><p>【Msg】:<div><input id="msg" name="msg" type="text" value="hello WebSocket2"></div><p>【第一步操作:】:<div><button onclick="openSocket()">开启socket</button><button onclick="openSocket1()">开启socket2</button></div><p>【第二步操作:】:<div><button onclick="sendMessage()">发送消息</button><button onclick="sendMessage1()">发送消息2</button></div>
</body></html>

http://www.ppmy.cn/embedded/40947.html

相关文章

如何判断海外住宅ip的好坏?

在海外IP代理中&#xff0c;住宅IP属于相对较好的资源&#xff0c;无论是用于工作、学习、还是娱乐&#xff0c;都能得到较好的使用效果。作为用户&#xff0c;该如何判断海外住宅IP的好坏呢&#xff1f; 稳定性与可靠性&#xff1a;海外住宅IP相比动态IP地址&#xff0c;通常具…

交通地理信息系统实习教程(二)

这篇文章服务于GIS背景用户以及有志于GIS的朋友 操作源数据位置&#xff1a;【免费】交通地理信息系统实习二源数据资源-CSDN文库 软件安装包位置&#xff1a;【免费】TransCad-交通地理信息系统软件资源-CSDN文库 一、最短路径分析 1.1软件启动说明 这里需要给出一个必要的…

数据结构——栈

文章目录 一、 栈的概念及结构二、栈的实现定义栈栈的初始化栈的销毁入栈出栈返回栈顶数据判空栈数据个数 三、栈的代码Stack.hStack.ctest.c 一、 栈的概念及结构 栈&#xff1a;一种特殊的线性表&#xff0c;其只允许在固定的一端进行插入和删除元素操作。 进行数据插入和…

Redis缓存双删(使用Redis如何保证数据库和缓存之间的同步)

使用Redis如何保证数据库和缓存之间的同步 通常我们有以下几种策略&#xff1a; 先修改数据库再更新缓存&#xff08;不建议&#xff09;&#xff1a;该策略的问题是如果数据库更新成功了Redis 修改失败了&#xff0c;也会导致不同步的问题 先修改缓存再更新数据库&#xff0…

Electron 报错:WinState is not a constructor

文章目录 问题分析 问题 在使用 electron-win-state 库时报错如下 代码如下&#xff1a; const WinState require(electron-win-state) const winState new WinState({ defaultWidth: 800,defaultHeight: 600,// other winState options, see below })const browserWindow…

出差——蓝桥杯十三届2022国赛大学B组真题

问题分析 该题属于枚举类型&#xff0c;遍历所有情况选出符合条件的即可。因为只需要派两个人&#xff0c;因此采用两层循环遍历每一种情况。 AC_Code #include <bits/stdc.h> using namespace std; string str;//选择的两人 bool ok(){if(str.find("A")!-1…

微调大模型学习记录

微调大模型基本思路 一般来说, 垂直领域的现状就是大家积累很多垂域数据,从现实出发,第一步可以先做增量训练.所以会把模型分成3个阶段: (1)、第一阶段:(Continue PreTraining)增量预训练&#xff0c;在海量领域文档数据&#xff08;领域知识&#xff09;上二次预训练base模型…

使用 PXE+Kickstart 批量网络自动装机

前言&#xff1a; 正常安装系统的话使用u盘一个一个安装会非常慢&#xff0c;所以批量安装的技术就出来了。 一、 概念 PXE &#xff08;Preboot eXecute Environment&#xff0c;预启动执行环境&#xff09;是由 Intel 公司开发的技术&#xff0c;可以让计算机通过网络来启动…