springboot整合websocket实现聊天室对话
要实现Spring Boot整合WebSocket实现聊天室对话,你需要遵循以下步骤:
1. 添加依赖
在你的pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. 配置WebSocket
创建一个配置类,继承AbstractWebSocketMessageBrokerConfigurer,并重写相关方法:
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").withSockJS();
}
}
3. 创建消息控制器
创建一个控制器类,用于处理客户端发送的消息:
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class ChatController {
@MessageMapping("/send")
@SendTo("/topic/messages")
public String handleMessage(String message) {
return message;
}
}
4. 前端页面
创建一个HTML页面,用于显示聊天室和发送消息的表单:
<!DOCTYPE html>
<html>
<head>
<title>Chat Room</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.0/sockjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
</head>
<body>
<div id="chatroom">
<ul id="messages"></ul>
</div>
<form id="form">
<input type="text" id="input" placeholder="Type your message here...">
<button type="submit">Send</button>
</form>
<script>
var socket = new SockJS('/chat');
var stompClient = Stomp.over(socket);
var messagesElement = document.getElementById('messages');
var formElement = document.getElementById('form');
var inputElement = document.getElementById('input');
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/messages', function (message) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(message.body));
messagesElement.appendChild(li);
});
});
formElement.addEventListener('submit', function (event) {
event.preventDefault();
stompClient.send("/app/send", {}, inputElement.value);
inputElement.value = '';
});
</script>
</body>
</html>
现在,你可以运行你的Spring Boot应用程序,访问http://localhost:8080,在聊天室中发送和接收消息。