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

Spring boot使用websocket实现在线聊天

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();}}

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.lryc.cn/news/348468.html

相关文章:

  • 品牌设计理念和logo设计方法
  • Python | Leetcode Python题解之第88题合并两个有序数组
  • vscode新版本remotessh服务端报`GLIBC_2.28‘ not found解决方案
  • 盘他系列——oj!!!
  • 洛谷 P2657 [SCOI2009] windy 数 题解 数位dp
  • Python爬虫入门:网络世界的宝藏猎人
  • 【NodeMCU实时天气时钟温湿度项目 6】解析天气信息JSON数据并显示在 TFT 屏幕上(心知天气版)
  • 重构四要素:目的、对象、时机和方法
  • 基于Echarts的大数据可视化模板:服务器运营监控
  • Python3 笔记:Python的常量
  • 【Linux】自动化构建工具make/Makefile和git介绍
  • C语言—关于字符串(编程实现部分函数功能)
  • picoCTF-Web Exploitation-Trickster
  • SSH 免密登录,设置好仍然需要密码登录解决方法
  • 【斑马打印机】web前端页面通过BrowserPrint API连接斑马打印机进行RFID条形码贴纸打印
  • DigitalOcean 应用托管更新:应用端到端运行时性能大幅改进
  • c/c++对于char*的理解(联合string容器)
  • Web前端三大主流框架是什么?
  • 一个基于servlet的MVC项目-登录验证
  • Windows 11 下 kafka 的安装踩坑
  • 二维数组:行列互换/求最大值及其所在位置/求各行各列的和/矩阵乘积/深入理解二维数组
  • The Onion Router-洋葱
  • 自动化工具 Ansible:playbooks 剧本编写
  • AttributeError: module ‘flask.app‘ has no attribute ‘route‘
  • 在云计算与人工智能中,7ECloud扮演着什么样的角色
  • 视频推拉流EasyDSS视频直播点播平台如何优先展示正在直播的直播间?
  • JavaEE之线程(4)——线程安全、线程安全的原因,synchronized关键字
  • Python3 笔记:分支结构
  • 《TAM》论文笔记(上)
  • 【Java的抽象类和接口】