1.创建springboot项目,引入spring-boot-starter-websocket依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
全部依赖如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.10</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.cherry</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- // springboot整合websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.创建一个TextWebSocketHandler的子类,重写handleTextMessage、afterConnectionEstablished、afterConnectionClosed方法
handleTextMessage()
handleTextMessage()方法通过英文方法名可知,用于处理文本信息。它有两个参数分别是:WebSocketSession和TextMessage。WebSocketSession可以通过sendMessage将消息发送给前台。TextMessage通过调用getPayload()接收前台消息体。
afterConnectionEstablished()
afterConnectionEstablished方法通过英文方法名可知,用于连接确立之后。
通过WebSocketSession的sendMessage方法,将创建的TextMessage对象给前台。
afterConnectionClosed
afterConnectionClosed方法用于连接关闭之后。参数有WebSocketSession和CloseStatus。WebSocketSession的方法sendMessage可以向前台发送消息,CloseStatus的getReason方法获得关闭的原因。
package com.cherry.demo.handler;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
@Component
public class MyHandler extends TextWebSocketHandler {
// 客户端想服务器发消息
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws IOException {
// 接收客户端的消息 message.getPayload()消息体
System.out.println("获取到消息 >> " + message.getPayload());
session.sendMessage(new TextMessage("消息已收到"));
// 向服务端发送消息
if(message.getPayload().equals("10")){
for (int i = 0; i < 10; i++) {
session.sendMessage(new TextMessage("消息 -> " + i));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 建议连接时
@Override
public void afterConnectionEstablished(WebSocketSession session) throws
Exception {
session.sendMessage(new TextMessage("欢迎连接到ws服务"));
}
// 关闭连接
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
throws Exception {
System.out.println("断开连接!");
}
}
3.创建WebSocketConfigurer接口的子类,重写registerWebSocketHandlers方法。
registerWebSocketHandlers()方法参数是WebSocketHandlerRegistry 。调用WebSocketHandlerRegistry 的addHandler方法传递处理器和路径。处理器参数是上一步创建的TextWebSocketHandler 的子类。路径是客户端调用时跟在端口后的路径。再调用WebSocketHandlerRegistry 的setAllowedOrigins方法传递星号,允许跨域访问。
WebSocketHandlerRegistry
addHandler()方法第一个传输传递处理器,第一个参数传递路径
setAllowedOrigins()方法设置允许源,传递星号,否则跨域。
import com.cherry.demo.handler.MyHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Autowired
private MyHandler myHandler;
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(this.myHandler, "/ws").setAllowedOrigins("*");
}
}