使用Spring Boot和WebSocket构建持久的一对一聊天应用程序
时间: 2023-12-03 20:43:31 浏览: 88
使用Spring Boot和WebSocket构建一对一聊天应用程序是非常简单的。下面是一些步骤:
1. 首先,在pom.xml中添加以下依赖项:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2. 创建一个WebSocket配置类,并添加@EnableWebSocket注解:
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new ChatHandler(), "/chat");
}
}
```
3. 创建一个WebSocket处理程序:
```java
public class ChatHandler extends TextWebSocketHandler {
private Map<WebSocketSession, String> sessions = new ConcurrentHashMap<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.put(session, session.getId());
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String sessionId = sessions.get(session);
session.sendMessage(new TextMessage(sessionId + ": " + message.getPayload()));
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.remove(session);
}
}
```
4. 创建一个简单的HTML页面来测试应用程序:
```html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
var socket = new WebSocket("ws://" + location.host + "/chat");
socket.onopen = function() {
console.log("Connected");
};
socket.onmessage = function(event) {
console.log(event.data);
$("#chat").append("<p>" + event.data + "</p>");
};
$(function() {
$("form").submit(function() {
var message = $("#message").val();
socket.send(message);
$("#message").val("");
return false;
});
});
</script>
</head>
<body>
<form>
<input type="text" id="message">
<button type="submit">Send</button>
</form>
<div id="chat"></div>
</body>
</html>
```
5. 运行应用程序并访问HTML页面。在不同的浏览器窗口中打开相同的页面,并尝试发送消息。您应该能够在两个窗口之间进行双向通信。
这就是使用Spring Boot和WebSocket构建一对一聊天应用程序的基本步骤。您可以根据需要调整代码以满足您的需求。
阅读全文