springboot + websocket 完整配置步骤
时间: 2023-08-16 11:10:26 浏览: 166
以下是使用Spring Boot和WebSocket的完整配置步骤:
1. 创建一个Spring Boot项目并添加相关依赖:
在`pom.xml`文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2. 创建WebSocket处理器:
```java
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
@Component
public class MyWebSocketHandler implements WebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 当WebSocket连接建立时执行的逻辑
}
@Override
public void handleMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理接收到的WebSocket消息
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
// 当WebSocket连接关闭时执行的逻辑
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
// 处理传输错误的逻辑
}
}
```
3. 配置WebSocket:
```java
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 {
private final MyWebSocketHandler webSocketHandler;
@Autowired
public WebSocketConfig(MyWebSocketHandler webSocketHandler) {
this.webSocketHandler = webSocketHandler;
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(webSocketHandler, "/websocket")
.setAllowedOrigins("*");
}
}
```
4. 在应用程序的入口类上添加`@EnableWebSocket`注解:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
5. 创建控制器:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class WebSocketController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public String greeting(String message) {
return "Hello, " + message + "!";
}
}
```
在上述代码中,`@MessageMapping`注解用于指定接收WebSocket消息的目标地址,`@SendTo`注解用于指定发送消息的目标地址。
6. 创建前端页面:
在你的前端页面中,使用JavaScript连接到WebSocket服务器并发送消息,可以使用`Stomp.js`和`SockJS`库来简化操作。例如:
```javascript
var stompClient = null;
function connect() {
var socket = new SockJS('/websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
stompClient.subscribe('/topic/greetings', function(response) {
var message = JSON.parse(response.body);
showMessage(message);
});
});
}
function showMessage(message) {
// 处理接收到的消息
}
function sendMessage(message) {
stompClient.send("/hello", {}, message);
}
```
在上述代码中,`connect()`函数用于建立WebSocket连接,`showMessage()`函数用于处理接收到的消息,`sendMessage()`函数用于发送消息。
7. 运行应用程序:
运行Spring Boot应用程序,访问前端页面,即可进行WebSocket通信。
以上是使用Spring Boot和WebSocket的完整配置步骤。你可以根据自己的需求进行调整和扩展。希望对你有所帮助!如有更多问题,请随时提问。
阅读全文