SpringBoot+WebSocket
1、导入包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.7.0</version>
</dependency>
2、websocket配置类
实现WebSocketConfigurer接口的类只能生效一个,使用时要避免多个类实现WebSocketConfigurer接口。
实现WebSocketConfigurer接口,实现registerWebSocketHandlers()方法,配置处理类,连接路径,作用域,拦截器等。
将拦截器HandshakeInterceptor 作为内部类写在配置类里,分别是前置拦截和后置拦截,前置拦截一般用于提取请求中的信息,用于验证和区分不同的用户。
package com.hsh.websocketproject.config;
import com.hsh.websocketproject.handler.MyWebSocketHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
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 org.springframework.web.socket.server.HandshakeInterceptor;
import java.util.Map;
/**
* @author hsh
* @date 2023/7/24 4:11
*/
@Configuration //告诉SpringBoot这是一个配置类,让SpringBoot加载配置
@EnableWebSocket //用于开启注解接收和发送消息
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyWebSocketHandler(), "/ws")//设置处理类和连接路径
.setAllowedOrigins("*") //设置作用域
.addInterceptors(new MyWebSocketInterceptor());//设置拦截器
}
/**
* 自定义拦截器拦截WebSocket请求
*/
class MyWebSocketInterceptor implements HandshakeInterceptor {
//前置拦截一般用来注册用户信息,绑定 WebSocketSession
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
System.out.println("前置拦截~~");
String userName = "hsh";
attributes.put("userName", userName);
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Exception exception) {
System.out.println("后置拦截~~");
}
}
}
3、编写处理器类
afterConnectionEstablished :连接成功后调用。
handleMessage :处理发送来的消息。
handleTransportError: 连接出错时调用。
afterConnectionClosed :连接关闭后调用。
supportsPartialMessages :是否支持分片消息。(传输大文件才用得到,一般直接使用return false就可以了)
package com.hsh.websocketproject.handler;
import org.springframework.web.socket.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author hsh
* @date 2023/7/24 4:50
*/
public class MyWebSocketHandler implements WebSocketHandler {
//所有连接的集合
private static final Map<String, WebSocketSession> SESSIONS = new ConcurrentHashMap<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
String userName = session.getAttributes().get("userName").toString();
SESSIONS.put(userName, session);
System.out.println("成功建立连接~ userName: " + userName);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
String msg = message.getPayload().toString();
System.out.println(msg);
String userName = session.getAttributes().get("userName").toString();
sendMessage(userName,"服务器收到消息收到"+userName+"发送的消息,消息内容为:"+msg);
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
System.out.println("连接出错");
if (session.isOpen()) {
session.close();
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
String userName = session.getAttributes().get("userName").toString();
System.out.println(userName + "的连接已关闭,status:" + closeStatus);
}
@Override
public boolean supportsPartialMessages() {
return false;
}
/**
* 指定发消息
*
* @param message
*/
public static void sendMessage(String userName, String message) {
WebSocketSession webSocketSession = SESSIONS.get(userName);
if (webSocketSession == null || !webSocketSession.isOpen()) return;
try {
webSocketSession.sendMessage(new TextMessage(message));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 群发消息
*
* @param message
*/
public static void fanoutMessage(String message) {
SESSIONS.keySet().forEach(us -> sendMessage(us, message));
}
}
4、测试连接
在浏览器控制台逐条输入文章来源:https://www.toymoban.com/news/detail-809319.html
//新建一个WebSocket对象,设置好长连接的地址,并建立链接
ws = new WebSocket("ws://localhost:8800/ws");
//收到服务端信息时把消息打印在控制台
ws.onmessage=function(data){console.log(data)};
//向服务器发送消息
ws.send('向服务器发送的消息!');
//使用结束后,不要忘记关闭长连接
ws.close();
websocket浏览器截图
websocket服务端截图
文章来源地址https://www.toymoban.com/news/detail-809319.html
到了这里,关于使用SpringBoot集成的WebSocket实现长连接的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!