最简单入门的SpringBoot+Vue项目用WebSoket完整教程代码,做客服,即时通信的看过来!

本文主要是介绍最简单入门的SpringBoot+Vue项目用WebSoket完整教程代码,做客服,即时通信的看过来!,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

后端原理不是很复杂 每次用户连接到服务端的时候会携带一个username,连接成功之后后端把username和当前soket添加到Map中

webSocketMap.put(username, this);

需要给指定用户发送消息的时候就通过username获取WebSoketServer通过.getBasicRemote().sendText()向用户发送消息

 for (Map.Entry<String, SongWebSoketServer> server : webSocketMap.entrySet()) {if(server.getKey().equals("接收消息的用户名")){server.getValue().session.getBasicRemote().sendText("想要发送的消息");}}

需要发送复杂消息的情况下可以New一个JSON对象

	JSONObject jsonObject = new JSONObject();jsonObject.put("code", 200);jsonObject.put("message", message);jsonObject.toJSONString();

完整代码:

前端页面中比较简单

<template><el-input v-model="content" /><el-button @click="send">发送</el-button>
</template>
<script>
export default {data() {return {socket: "",content: '',}},created() {this.init();},methods: {init: function () {if (typeof (WebSocket) === "undefined") {alert("您的浏览器不支持socket");} else {// 需要服务器配置开放后端端口// 实例化socketthis.socket = new WebSocket("ws://localhost:8080/websocket/" + "username");// 监听socket连接this.socket.onopen = this.open;// 监听socket错误信息this.socket.onerror = this.error;// 监听socket消息this.socket.onmessage = this.getMessage;}},open: function () {console.log("socket连接成功");},error: function () {console.log("连接错误");},getMessage: function (msg) {console.log(msg)},send: function () {this.socket.send(this.content);this.content = "";},close: function () {console.log("socket已经关闭");}},destroyed() {this.socket.onclose = this.close; // 销毁监听}
}
</script>
<style lang="scss" scoped>
</style>

SpirngBoot项目中创建WebSoket模块

pom中引入
 <!-- SpringBoot Websocket --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
新建WebSoketServer
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;@Component
@Service
@ServerEndpoint(value = "/websocket/{username}")
public class WebSoketServer {static final Logger loggger = LoggerFactory.getLogger(WebSoketServer.class);private static ConcurrentHashMap<String, WebSoketServer> webSocketMap = new ConcurrentHashMap<>();  // 用来存放每个客户端对应的MyWebSocket对象。   private Session session;    private String username = "";   // 接收username// 打开连接@OnOpenpublic void onOpen(Session session, @PathParam("username") String username) throws IOException {this.session = session;this.username = username;if (webSocketMap.containsKey(username)) {webSocketMap.remove(username);webSocketMap.put(username, this);} else {webSocketMap.put(username, this);}loggger.info("用户:" + username + "连接:当前在线人数为:" + webSocketMap.size());}// 关闭连接@OnClosepublic void onClose() {if (webSocketMap.containsKey(username)) {webSocketMap.remove(username);}loggger.info("用户" + username + "退出:当前在线人数为:" + webSocketMap.size());}// 接收消息@OnMessagepublic void onMessage(String message, Session session) {loggger.info("用户" + username + "消息:内容:" + message);}// 发送自定义消息public static void sendInfo(String message, String username) {loggger.info("发送消息到:" + username + ",内容:" + message);if (StringUtils.isNotBlank(username) && webSocketMap.containsKey(username)) {try {webSocketMap.get(username).sendMessage(message);} catch (Exception e) {loggger.error(e.getMessage(), e);}} else {loggger.error("用户" + username + ",不在线!");}}@OnErrorpublic void onError(Session session, Throwable error) {loggger.error("用户" + username + "错误:原因:" + error.getMessage());error.printStackTrace();}// 推送消息public void sendMessage(String message) throws IOException {this.session.getBasicRemote().sendText(message);}
}

这篇关于最简单入门的SpringBoot+Vue项目用WebSoket完整教程代码,做客服,即时通信的看过来!的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/279854

相关文章

Spring LDAP目录服务的使用示例

《SpringLDAP目录服务的使用示例》本文主要介绍了SpringLDAP目录服务的使用示例... 目录引言一、Spring LDAP基础二、LdapTemplate详解三、LDAP对象映射四、基本LDAP操作4.1 查询操作4.2 添加操作4.3 修改操作4.4 删除操作五、认证与授权六、高级特性与最佳

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

SpringSecurity JWT基于令牌的无状态认证实现

《SpringSecurityJWT基于令牌的无状态认证实现》SpringSecurity中实现基于JWT的无状态认证是一种常见的做法,本文就来介绍一下SpringSecurityJWT基于令牌的无... 目录引言一、JWT基本原理与结构二、Spring Security JWT依赖配置三、JWT令牌生成与

Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码

《Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码》:本文主要介绍Java中日期时间转换的多种方法,包括将Date转换为LocalD... 目录一、Date转LocalDateTime二、Date转LocalDate三、LocalDateTim

如何配置Spring Boot中的Jackson序列化

《如何配置SpringBoot中的Jackson序列化》在开发基于SpringBoot的应用程序时,Jackson是默认的JSON序列化和反序列化工具,本文将详细介绍如何在SpringBoot中配置... 目录配置Spring Boot中的Jackson序列化1. 为什么需要自定义Jackson配置?2.

Java中使用Hutool进行AES加密解密的方法举例

《Java中使用Hutool进行AES加密解密的方法举例》AES是一种对称加密,所谓对称加密就是加密与解密使用的秘钥是一个,下面:本文主要介绍Java中使用Hutool进行AES加密解密的相关资料... 目录前言一、Hutool简介与引入1.1 Hutool简介1.2 引入Hutool二、AES加密解密基础

Spring Boot项目部署命令java -jar的各种参数及作用详解

《SpringBoot项目部署命令java-jar的各种参数及作用详解》:本文主要介绍SpringBoot项目部署命令java-jar的各种参数及作用的相关资料,包括设置内存大小、垃圾回收... 目录前言一、基础命令结构二、常见的 Java 命令参数1. 设置内存大小2. 配置垃圾回收器3. 配置线程栈大小

SpringBoot实现微信小程序支付功能

《SpringBoot实现微信小程序支付功能》小程序支付功能已成为众多应用的核心需求之一,本文主要介绍了SpringBoot实现微信小程序支付功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作... 目录一、引言二、准备工作(一)微信支付商户平台配置(二)Spring Boot项目搭建(三)配置文件

解决SpringBoot启动报错:Failed to load property source from location 'classpath:/application.yml'

《解决SpringBoot启动报错:Failedtoloadpropertysourcefromlocationclasspath:/application.yml问题》这篇文章主要介绍... 目录在启动SpringBoot项目时报如下错误原因可能是1.yml中语法错误2.yml文件格式是GBK总结在启动S

Spring中配置ContextLoaderListener方式

《Spring中配置ContextLoaderListener方式》:本文主要介绍Spring中配置ContextLoaderListener方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录Spring中配置ContextLoaderLishttp://www.chinasem.cntene