ssm 整合websocket
时间: 2023-08-29 10:10:31 浏览: 209
ssm+websocket
在SSM框架中整合WebSocket,可以通过以下步骤实现:
1. 添加Maven依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>5.3.9</version>
</dependency>
```
2. 配置WebSocket
在Spring的配置文件中添加以下配置:
```xml
<!-- 配置WebSocket -->
<bean class="org.springframework.web.socket.server.standard.ServerEndpointExporter"/>
```
3. 编写WebSocket处理器
创建一个类,实现WebSocketHandler接口,处理WebSocket消息的接收和发送,例如:
```java
@Component
@ServerEndpoint("/websocket")
public class WebSocketHandler {
private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<>());
@OnOpen
public void onOpen(Session session) {
sessions.add(session);
System.out.println("WebSocket connected: " + session.getId());
}
@OnMessage
public void onMessage(String message, Session session) throws IOException {
System.out.println("WebSocket received message: " + message);
for (Session s : sessions) {
if (s.isOpen()) {
s.getBasicRemote().sendText(message);
}
}
}
@OnClose
public void onClose(Session session) {
sessions.remove(session);
System.out.println("WebSocket disconnected: " + session.getId());
}
@OnError
public void onError(Throwable throwable) {
throwable.printStackTrace();
}
}
```
4. 创建WebSocket连接
在前端页面中,使用JavaScript创建WebSocket连接,例如:
```javascript
var socket = new WebSocket("ws://" + window.location.host + "/websocket");
socket.onopen = function() {
console.log("WebSocket connected");
};
socket.onmessage = function(event) {
console.log("WebSocket received message: " + event.data);
};
socket.onclose = function() {
console.log("WebSocket disconnected");
};
socket.onerror = function(event) {
console.error("WebSocket error: " + event);
};
function sendMessage() {
var message = document.getElementById("message").value;
socket.send(message);
}
```
在HTML页面中添加一个文本输入框和一个按钮,用于发送消息:
```html
<input id="message" type="text">
<button onclick="sendMessage()">Send</button>
```
至此,SSM框架与WebSocket的整合完成。
阅读全文