第一种:SpringBoot官网提供了一种websocket的集成方式

第二种:javax.websocket中提供了元注解的方式

下面讲解简单的第二种

添加依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!--<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>-->
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<!-- 打包成war包这个一定要设置为provided,不然websocket连不上 -->
<scope>provided</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

配置类

WebSocketConfig.java

package com.meeno.trainsys.websocket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; /**
* @description: WebSocketConfig类
* @author: Wzq
* @create: 2020-04-15 11:22
*/
//当我们使用外部Tomcat时,项目的管理权将会由Spring交接至Tomcat。 
// 而Tomcat7及后续版本是对websocket直接支持的,且我们所使用的jar包也是tomcat提供的。 
// 但是我们在WebSocketConfig中将ServerEndpointExporter指定给Spring管理。
// 而部署后ServerEndpoint是需要Tomcat直接管理才能生效的。
// 所以此时即就是此包的管理权交接失败,那肯定不能成功了。
// 最后我们需要将WebSocketConfig中的bean配置注释掉
@Configuration
public class WebSocketConfig { // 本地开发打开注释,打包成war注释掉再打包
// @Bean
// public ServerEndpointExporter serverEndpointExporter() {
// return new ServerEndpointExporter();
// } }

MeetingWebSocket.java

package com.meeno.trainsys.websocket.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.meeno.framework.constants.Constants;
import com.meeno.framework.util.JsonUtils;
import com.meeno.trainsys.user.service.UserMessageService;
import com.meeno.trainsys.user.view.MeetingEmployeeChatListView;
import com.meeno.trainsys.user.view.UserMessageListView;
import com.meeno.trainsys.websocket.constants.SocketConstants;
import com.meeno.trainsys.websocket.model.MeetingSocketModel;
import com.meeno.trainsys.websocket.view.MeetingSocketView;
import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; /**
* @description:
* @author: Wzq
* @create: 2020-04-15 11:30
*/
@Component
@ServerEndpoint("/websocket/{meetingId}/{empId}")
@Log
public class MeetingWebSocket { private static UserMessageService userMessageService; @Autowired
public void setUserMessageService(UserMessageService userMessageService){
MeetingWebSocket.userMessageService = userMessageService;
} // concurrent包的线程安全Map,用来存放每个客户端对应的MyWebSocket对象。 Long为会议室id
private static ConcurrentHashMap<String,MeetingWebSocket> webSocketMap = new ConcurrentHashMap<String,MeetingWebSocket>(); //会议id
private Long meetingId;
//当前用户id
private Long userId;
// 当前聊天对象Session
private Session session;
// 未读数量
private Integer notReadNum; /**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session, @PathParam("meetingId") Long meetingId,@PathParam("empId") Long empId) {
log.info("onOpen->meetingId:" + meetingId);
//创建一个会议webSocket
this.session = session;
this.meetingId = meetingId;
this.userId = empId;
webSocketMap.put(meetingId + "-" + userId,this);
} /**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
log.info("onClose!");
//那个关闭了连接清空map
if(this.meetingId != null && this.userId != null){
String keyStr = this.meetingId + "-" + this.userId;
webSocketMap.remove(keyStr);
}
} /**
* 收到客户端消息后调用的方法
* @param message
*/
@OnMessage
public void onMessage(String message, Session session, @PathParam("meetingId") Long meetingId,@PathParam("empId") Long empId){
log.info("onMessage!" + message);
//发送消息给指定的人
this.sendMessageByUserId(1,model.getMeetingId(),model.getTargetEmpId()); } /**
* 发生错误时调用
*/
@OnError
public void onError(Session session, Throwable error){
log.info("webSocket发生错误!");
error.printStackTrace();
} /**
* 根据会议id和用户id获取Socket
* @param meetingId
* @param userId
*/
public static MeetingWebSocket getSocketByMeetingAndUserId(Long meetingId,Long userId){
for (String keyStr : webSocketMap.keySet()) {
String[] splitStr = keyStr.split("-");
String keyMeetingIdStr = splitStr[0];
if(meetingId.toString().equals(keyMeetingIdStr)){
if(webSocketMap.get(keyStr).userId.equals(userId)){
MeetingWebSocket meetingWebSocket = webSocketMap.get(keyStr);
return meetingWebSocket;
}
}
}
return null;
} /**
* 根据会议和用户id发送消息
* @param msg
* @param meetingId
* @param userId
*/
private void sendMessageByUserId(String msg,Long meetingId,Long userId){
for (String keyStr : webSocketMap.keySet()) {
String[] splitStr = keyStr.split("-");
String keyMeetingIdStr = splitStr[0];
if(meetingId.toString().equals(keyMeetingIdStr)){
if(webSocketMap.get(keyStr).userId.equals(userId)){
MeetingWebSocket meetingWebSocket = webSocketMap.get(keyStr);
meetingWebSocket.sendMessage(msg);
}
}
}
}
/**
* 发送消息
* @param msg
*/
private void sendMessage(String msg){
try {
this.session.getBasicRemote().sendText(msg);
} catch (IOException e) {
e.printStackTrace();
}
} }

测试连接

SpringBoot集成websocket(java注解方式)的更多相关文章

  1. springboot集成websocket的两种实现方式

    WebSocket跟常规的http协议的区别和优缺点这里大概描述一下 一.websocket与http http协议是用在应用层的协议,他是基于tcp协议的,http协议建立链接也必须要有三次握手才能 ...

  2. springboot集成websocket实现向前端浏览器发送一个对象,发送消息操作手动触发

    工作中有这样一个需示,我们把项目中用到代码缓存到前端浏览器IndexedDB里面,当系统管理员在后台对代码进行变动操作时我们要更新前端缓存中的代码怎么做开始用想用版本方式来处理,但这样的话每次使用代码 ...

  3. SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版)

    SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版) ================================ ©Copyright 蕃薯耀 2 ...

  4. springboot集成websocket实现大文件分块上传

    遇到一个上传文件的问题,老大说使用http太慢了,因为http包含大量的请求头,刚好项目本身又集成了websocket,想着就用websocket来做文件上传. 相关技术 springboot web ...

  5. SpringBoot集成websocket发送后台日志到前台页面

    业务需求 后台为一个采集系统,需要将采集过程中产生的日志实时发送到前台页面展示,以便了解采集过程. 技能点 SpringBoot 2.x websocket logback thymeleaf Rab ...

  6. SpringBoot集成WebSocket【基于纯H5】进行点对点[一对一]和广播[一对多]实时推送

    代码全部复制,仅供自己学习用 1.环境搭建 因为在上一篇基于STOMP协议实现的WebSocket里已经有大概介绍过Web的基本情况了,所以在这篇就不多说了,我们直接进入正题吧,在SpringBoot ...

  7. spring的Java注解方式

    以往我们在使用spring的时候都是用一堆<>这个玩意(尖括号)的xml文件来配置spring,在xml里都是"xxx"来配置需要的内容信息,在"" ...

  8. SpringBoot集成websocket(Spring方式)

    SpringWebSocketConfig配置 package com.meeno.chemical.socket.task.config; import com.meeno.chemical.soc ...

  9. Springboot集成WebSocket通信全部代码,即扣即用。

    websocket通信主要来自两个类以及一个测试的html页面. MyHandler 和 WebSocketH5Config,下面全部代码 MyHandler类全部代码: package com.un ...

随机推荐

  1. (精)题解 guP2860 [USACO06JAN]冗余路径Redundant Paths

    (写题解不容易,来我的博客玩玩咯qwq~) 该题考察的知识点是边双连通分量 边双连通分量即一个无向图中,去掉一条边后仍互相连通的极大子图.(单独的一个点也可能是一个边双连通分量) 换言之,一个边双连通 ...

  2. [WPF] 使用 Visual Studio App Center 持续监视应用使用情况和问题

    1. 什么是AppCenter Visual Studio App Center 是几个常见移动开发和云集成服务(如持续集成.持续交付和自动 UI 测试等服务)的集合. 这些 App Center 服 ...

  3. golang拾遗:内置函数len的小知识

    len是很常用的内置函数,可以测量字符串.slice.array.channel以及map的长度/元素个数. 不过你真的了解len吗?也许还有一些你不知道的小知识. 我们来看一道GO101的题目,这题 ...

  4. C++ Primer Plus 第四章 复合类型 学习笔记

    第四章 复合类型 1. 数组概述 1.1 数组的定义 数组(array)是一种数据格式,能够存储多个同类型的值.每个值都存储在一个独立的数组元素中,计算机在内存中依次存储数组的各个元素. 数组声明的三 ...

  5. Linux CentOS 7 在Apache服务器上安装SSL证书

    在开发微信小程序的时候,wx.request请求的地址必须是https的,所以只能重新配置服务器. 域名和服务器都是在阿里云上买的,系统是CentOS7,安装了Apache服务器.网上也找了一下,很多 ...

  6. Linux中tomcat随服务器自启动的设置方法

    1. cd到rc.local文件所在目录,一般在 /etc/rc.d/目录. 2. 将rc.local下载到本地windows系统中. 3. 编辑rc.local,将要启动的tomcat  /bin/ ...

  7. 第十八篇 -- GPIO学习

    先学习一下GPIO,网上各种找资料,拼凑,所以就不一一贴网址了. 一.GPIO GPIO的英文全称General-Purpose Input /Output Ports,中文意思是通用I/O端口 一个 ...

  8. 1.1 MATLAB系统环境

    专题一 MATLAB基础知识 1.1 MATLAB系统环境 1. 续行符(三个点) 2. 当前文件夹 先建立当前文件夹,再cd 3.工作区窗口 4.搜索路径       01当前文件夹下的程序文件 变 ...

  9. (JAVA2)写博客的好帮手:Typora

    (二)写博客的好帮手:Typora 推荐文本编辑器 :Typora 文件后缀 : xxx.md 安装步骤 打开浏览器搜索Typora 进入官网后,点击Download(下载) 选择自己的操作系统 选择 ...

  10. 一文彻底弄懂cookie、session、token

    前言 作为一个JAVA开发,之前有好几次出去面试,面试官都问我,JAVAWeb掌握的怎么样,我当时就不知道怎么回答,Web,日常开发中用的是什么?今天我们来说说JAVAWeb最应该掌握的三个内容. 发 ...