【WebSocket】在SSM项目中配置websocket
创始人
2024-05-31 14:53:48
0

在SSM项目中配置websocket

最近在ssm项目中配置了websocket,踩了很多坑,来分享一下

本文暂不提供发送消息等内容的代码逻辑(后续也许会补充),如果你直接复制这类可能会对配置造成更大的麻烦(博主就是复制了他人逻辑导致连接后秒断开连接,排查了很长时间),建议看完本文配置成功后,去其他文章或者github寻找相应代码逻辑

1.Maven依赖

首先是jackson的依赖

		com.fasterxml.jackson.corejackson-annotations2.3.0com.fasterxml.jackson.corejackson-core2.3.1com.fasterxml.jackson.corejackson-databind2.3.3

然后是spring关于websocket的依赖

		org.springframeworkspring-websocket${spring.version}org.springframeworkspring-messaging${spring.version}

这里的${spring.version}需要注意,一定要和自己的spring版本匹配,所以推荐用这种形式,而不是直接用x.x.x.RELEASE

另外在spring4.0.5.RELEASE之前与其以后,session获取参数的方法有些不同,需要注意

本文使用的是

4.2.5.RELEASE

注意:请删除所有关于javax的依赖,将本地的tomcat引入库中,否则可能会出现类型转换异常导致连接报错(你可以继续下面的步骤,如果在启动测试时出现该问题,再回来尝试解决)
在这里插入图片描述
在这里插入图片描述

2.配置类

首先在我们的项目中创建如下结构
在这里插入图片描述

当然也可以不使用这样的结构,如果你的项目中本来有config、Interceptor、handler包,可以将这些类放入其中

注意以下代码没有给出包名,如需复制请注意

首先是WebSocketConfig.java

import org.springframework.stereotype.Component;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;import javax.annotation.Resource;/*** WebScoket配置处理器*/
@Component
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {@ResourceMyWebSocketHandler handler;@ResourceHandShake handShake;public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {//浏览器支持websocketregistry.addHandler(handler, "/ws").addInterceptors(handShake);//浏览器不支持的话,需要socketjs引入支持registry.addHandler(handler, "/ws/sockjs").addInterceptors(handShake).withSockJS();}}

这个类的作用是配置websocket的链接地址,分为浏览器支持websocket和不支持websocket的情况,不支持可以引入sockjs(某些环境下使用这行代码会导致无法连接,不放心可以删去)

websocket连接地址是

ws://ip:端口号/项目名称/ws

ws与上述配置类相对应

这个连接地址是可以以?的形式传参数的,例如

"ws://ip:端口号/项目名称/ws?userId="+userId

第二个类是HandShake.java

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;import javax.servlet.http.HttpSession;
import java.util.Map;/*** Socket建立连接(握手)和断开*/
@Component
public class HandShake implements HandshakeInterceptor {@Overridepublic boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map attributes) throws Exception {// 1.获取sessionServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;HttpSession session = servletRequest.getServletRequest().getSession(false);// 2.从session中获取uidLong uid = (Long) session.getAttribute("uid");// 3.做正向判断,如果uid是空值直接返回false,拒绝握手if (uid == null){return false;}// 4.输出日志System.out.println("Websocket:用户[ID:" + uid + "]准备进行握手");// 5.将用户id存入mapattributes.put("uid", uid);// 6.可以进行握手return true;}@Overridepublic void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {System.out.println("after hand");}}

这个类是websocket的握手拦截器,会拦截websocket链接地址的请求,进行握手,不建议在该类中做业务处理

最后是MyWebSocketHandler.java

import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import java.io.IOException;/*** Socket处理器*/
@Component
public class MyWebSocketHandler implements WebSocketHandler {@Overridepublic void afterConnectionEstablished(WebSocketSession session)throws Exception {System.out.println("ConnectionEstablished");}@Overridepublic void handleMessage(WebSocketSession session, WebSocketMessage message) throws Exception {}/*** 消息传输错误处理*/@Overridepublic void handleTransportError(WebSocketSession session,Throwable exception) throws Exception {System.out.println("TransportError");}/*** 关闭连接后*/@Overridepublic void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {System.out.println("ConnectionClosed");}@Overridepublic boolean supportsPartialMessages() {return false;}
}

这个类是对websocket的各种状态作出相应的处理,如开头所说,本文不会给出相应的逻辑,防止出现错误,这里真的很坑

大体思路就是通过方法中的WebSocketSession获取到session中的用户id,再注入自己的userService(或者其他service层)去完成业务,同时可以在本类中使用ConcurrentHashMap或者直接开一个线程来实现同时在线人数等功能

发送信息的逻辑推荐对信息进行封装,构建实体类

此外你还可以创建一个相应的Controller,通过注入MyWebSocketHandler来建立相应功能的请求地址

import com.webchat.websocket.MyWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/websocket")
public class WebSocketController {@AutowiredMyWebSocketHandler handler;}

3.JS部分

最后是js部分

		let websocket = new WebSocket("ws://ip:端口号/项目名称/ws?userId="+userId);websocket.onmessage = function(event) {console.log(event.data)};websocket.onopen = function (event){console.log("连接成功")}websocket.onerror = function (event){console.log("连接错误")}websocket.onclose = function (event){console.log('websocket 断开: ' + event.code + ' ' + event.reason + ' ' + event.wasClean)}

注意更改地址

4.测试结果

测试结果如下
在这里插入图片描述
在这里插入图片描述
至此,ssm项目中配置websocket就完成了

如果在测试中出现其他错误,可以根据输出的event.code来匹配错误原因,如果连接后直接断开并显示1011请检查后端代码规范性

编码原因
1000正常关闭 当你的会话成功完成时发送这个代码
1001离开 因应用程序离开且不期望后续的连接尝试而关闭连接时,发送这一代码。服务器可能关闭,或者客户端应用程序可能关闭
1002协议错误 当因协议错误而关闭连接时发送这一代码
1003不可接受的数据类型 当应用程序接收到一条无法处理的意外类型消息时发送这一代码
1004保留 不要发送这一代码。根据 RFC 6455,这个状态码保留,可能在未来定义
1005保留 不要发送这一代码。WebSocket API 用这个代码表示没有接收到任何代码
1006保留 不要发送这一代码。WebSocket API 用这个代码表示连接异常关闭
1007无效数据 在接收一个格式与消息类型不匹配的消息之后发送这一代码。如果文本消息包含错误格式的 UTF-8 数据,连接应该用这个代码关闭
1008消息违反政策 当应用程序由于其他代码所不包含的原因终止连接,或者不希望泄露消息无法处理的原因时,发送这一代码
1009消息过大 当接收的消息太大,应用程序无法处理时发送这一代码(记住,帧的载荷长度最多为64 字节。即使你有一个大服务器,有些消息也仍然太大。)
1010需要扩展 当应用程序需要一个或者多个服务器无法协商的特殊扩展时,从客户端(浏览器)发送这一代码
1011意外情况 当应用程序由于不可预见的原因,无法继续处理连接时,发送这一代码
1015TLS失败(保留) 不要发送这个代码。WebSocket API 用这个代码表示 TLS 在 WebSocket 握手之前失败。
0 ~ 999禁止 1000 以下的代码是无效的,不能用于任何目的
1000 ~ 2999保留 这些代码保留以用于扩展和 WebSocket 协议的修订版本。按照标准规定使用这些代码,参见表 3-4
3000 ~ 3999需要注册 这些代码用于“程序库、框架和应用程序”。这些代码应该在 IANA(互联网编号分配机构)公开注册
4000 ~ 4999私有 在应用程序中将这些代码用于自定义用途。因为它们没有注册,所以不要期望它们能被其他 WebSocket广泛理解

相关内容

热门资讯

高中英语万能句子开头【精彩3... 高中英语万能句子开头 篇一A Journey to RememberTraveling is a w...
关于英语老师作文500字(优... 篇一:关于英语老师的重要性作为学生,我们每天都要上英语课。而我们的英语老师在我们学习英语的过程中起着...
写我的朋友的英语作文500字... Title: My Friend - Part OneMy FriendI am fortunate...
英语模仿给同学写信范文(精选... 英语模仿给同学写信范文 篇一Dear [Friend's Name],I hope this let...
动物英语作文:Pigeon鸽... 动物英语作文:Pigeon鸽子 篇一Pigeons are fascinating creature...
物流商业信件模板英语范文(优... 物流商业信件模板英语范文 篇一标题:合作邀请函Dear [收件人的姓名],我代表[你的公司名称],一...
参加节目成功通知范文英语56... 篇一:Successful Participation in ProgramDear [Name],...
描写地方的英语作文(优秀3篇... 描写地方的英语作文 篇一Title: A Serene Paradise: The Enchanti...
环境的英语作文【实用6篇】 环境的英语作文 篇一Protecting the Environment for a Better ...
英语作文及翻译【精简6篇】 英语作文及翻译 篇一Title: The Importance of Learning Englis...
享受当下英语作文【精彩3篇】 享受当下英语作文 篇一标题:The Importance of Living in the Pres...
英语作文感谢自己邮件范文(优... 英语作文感谢自己邮件范文 篇一Subject: Thanking Myself for Overco...
介绍我的数学老师英语作文【通... Introducing My Math Teacher - Article OneMy math t...
最尊敬的人英语作文(精彩6篇... 最尊敬的人英语作文 篇一:我的父亲My Respected FatherMy father is t...
英语结婚祝贺卡格式范文(实用... 英语结婚祝贺卡格式范文 篇一Congratulations on Your Wedding!Dear...
手表店铺简介范文英语优选21... 手表店铺简介范文英语 第一篇生日那天,妈妈在或与番给我买了一块手表。当妈妈送给我的时候,我高兴极了,...
幸福的英语作文(精彩6篇) 幸福的英语作文 篇一:The Pursuit of HappinessHappiness is a ...
网络上个人隐私英语作文【优质... 网络上个人隐私英语作文 篇一With the rapid development of the in...
作文题目考试共两百字(精选5... 作文题目考试共两百字 篇一追求卓越,成就未来在当今竞争激烈的社会中,追求卓越已经成为了许多人的共同目...
如何保持身体健康英语作文【精... 如何保持身体健康英语作文 篇一Title: Tips for Maintaining a Healt...