如何用springboot+websocket构建在线聊天室
时间: 2023-07-18 11:28:52 浏览: 138
下面是使用Spring Boot和WebSocket构建在线聊天室的步骤:
1. 新建一个Spring Boot项目,并添加WebSocket依赖。
2. 创建WebSocket配置类,配置WebSocket相关参数。代码如下:
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
// 注册WebSocket处理器
registry.addHandler(new ChatWebSocketHandler(), "/chat")
.setAllowedOrigins("*")
.addInterceptors(new HttpSessionHandshakeInterceptor());
}
}
```
3. 创建WebSocket处理器,实现WebSocketHandler接口,并处理WebSocket连接、关闭、错误和消息事件。代码如下:
```java
public class ChatWebSocketHandler extends TextWebSocketHandler {
private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 添加WebSocket会话
sessions.add(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// 移除WebSocket会话
sessions.remove(session);
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
// 处理WebSocket传输错误
session.close();
sessions.remove(session);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理WebSocket文本消息
String payload = message.getPayload();
for (WebSocketSession s : sessions) {
s.sendMessage(new TextMessage(payload));
}
}
}
```
4. 创建前端HTML页面,使用JavaScript连接WebSocket服务器,并处理WebSocket连接、关闭、错误和消息事件。代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>在线聊天室</title>
</head>
<body>
<div>
<label>用户名:</label>
<input type="text" id="username">
</div>
<div>
<label>消息:</label>
<input type="text" id="message">
<button onclick="sendMessage()">发送</button>
</div>
<div>
<label>聊天记录:</label>
<ul id="chatRecord"></ul>
</div>
<script>
var username = document.getElementById("username");
var message = document.getElementById("message");
var chatRecord = document.getElementById("chatRecord");
var webSocket = new WebSocket("ws://localhost:8080/chat");
webSocket.onopen = function () {
console.log("WebSocket已连接");
};
webSocket.onclose = function () {
console.log("WebSocket已关闭");
};
webSocket.onerror = function () {
console.log("WebSocket发生错误");
};
webSocket.onmessage = function (event) {
console.log("WebSocket收到消息:" + event.data);
var li = document.createElement("li");
li.innerHTML = event.data;
chatRecord.appendChild(li);
};
function sendMessage() {
var msg = username.value + ":" + message.value;
webSocket.send(msg);
message.value = "";
}
</script>
</body>
</html>
```
5. 运行Spring Boot应用程序,访问前端HTML页面,输入用户名和消息,点击发送按钮,即可实现在线聊天。
以上就是使用Spring Boot和WebSocket构建在线聊天室的步骤,希望对你有所帮助。
阅读全文