springboot websocket聊天室开发实例
时间: 2023-07-05 17:31:20 浏览: 77
websocket聊天室示例
5星 · 资源好评率100%
好的,下面是一个简单的 Spring Boot WebSocket 聊天室的开发实例:
1. 首先,创建一个 Spring Boot 项目,并添加所需的依赖:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>sockjs-client</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>stomp-websocket</artifactId>
<version>2.3.3</version>
</dependency>
</dependencies>
```
2. 创建一个 WebSocket 配置类:
```java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
}
```
3. 创建一个控制器类:
```java
@Controller
public class ChatController {
@MessageMapping("/chat")
@SendTo("/topic/messages")
public ChatMessage sendMessage(ChatMessage message) {
return message;
}
}
```
4. 创建一个聊天消息类:
```java
public class ChatMessage {
private String content;
private String sender;
// getters and setters
}
```
5. 创建一个 HTML 页面:
```html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat Example</title>
<script src="/webjars/sockjs-client/sockjs.min.js"></script>
<script src="/webjars/stomp-websocket/stomp.min.js"></script>
<script src="/js/app.js"></script>
</head>
<body>
<div>
<label>Username:</label>
<input type="text" id="username" />
</div>
<div>
<label>Message:</label>
<input type="text" id="message" />
<button onclick="sendMessage()">Send</button>
</div>
<div id="messages"></div>
</body>
</html>
```
6. 创建一个 JavaScript 文件:
```javascript
var stompClient = null;
function connect() {
var socket = new SockJS('/ws');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/messages', function(message) {
showMessage(JSON.parse(message.body));
});
});
}
function sendMessage() {
var username = document.getElementById('username').value;
var message = document.getElementById('message').value;
var chatMessage = {
content: message,
sender: username
};
stompClient.send("/app/chat", {}, JSON.stringify(chatMessage));
}
function showMessage(message) {
var messages = document.getElementById('messages');
var messageElement = document.createElement('div');
messageElement.innerHTML = '<strong>' + message.sender + '</strong>: ' + message.content;
messages.appendChild(messageElement);
}
connect();
```
7. 运行程序并访问页面,即可在聊天室中发送和接收消息。
希望这个实例能帮助你了解如何使用 Spring Boot 开发 WebSocket 聊天室。
阅读全文