SpringBoot使用WebSocket实现简单的网页一对一聊天功能的代码中包含html的语言
时间: 2023-04-02 10:01:41 浏览: 111
可以使用Thymeleaf模板引擎来实现包含html的语言,具体代码如下:
1. 在pom.xml文件中添加依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 在SpringBoot的配置文件中添加如下配置:
```
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
```
3. 创建一个WebSocket处理器类,实现WebSocketHandler接口,重写其中的方法:
```
@Component
public class ChatHandler implements WebSocketHandler {
private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
for (WebSocketSession s : sessions) {
if (s.isOpen()) {
s.sendMessage(message);
}
}
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
if (session.isOpen()) {
session.close();
}
sessions.remove(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
sessions.remove(session);
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
```
4. 创建一个Controller类,处理WebSocket请求:
```
@Controller
public class ChatController {
@Autowired
private ChatHandler chatHandler;
@GetMapping("/chat")
public String chat() {
return "chat";
}
@GetMapping("/chat/{username}")
public String chat(@PathVariable String username, Model model) {
model.addAttribute("username", username);
return "chat";
}
@Bean
public WebSocketHandlerAdapter handlerAdapter() {
return new WebSocketHandlerAdapter();
}
@Bean
public WebSocketHandler chatHandler() {
return new ChatHandler();
}
@Bean
public WebSocketConfigurer webSocketConfigurer() {
return new WebSocketConfigurer() {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(chatHandler, "/chat").setAllowedOrigins("*");
}
};
}
}
```
5. 创建一个Thymeleaf模板,实现网页聊天功能:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Chat</title>
</head>
<body>
<div>
<input type="text" id="username" placeholder="请输入用户名">
<button onclick="login()">登录</button>
</div>
<div id="chat" style="display: none">
<div>
<span th:text="'欢迎您,' + ${username}"></span>
<button onclick="logout()">退出</button>
</div>
<div>
<textarea id="message" placeholder="请输入消息"></textarea>
<button onclick="send()">发送</button>
</div>
<div id="messages"></div>
</div>
<script type="text/javascript">
var username = null;
var socket = null;
function login() {
username = document.getElementById("username").value;
if (username == "") {
alert("请输入用户名");
return;
}
document.getElementById("username").value = "";
document.getElementById("chat").style.display = "block";
socket = new WebSocket("ws://" + window.location.host + "/chat");
socket.onmessage = function(event) {
var message = JSON.parse(event.data);
var div = document.createElement("div");
div.innerText = message.username + ": " + message.message;
document.getElementById("messages").appendChild(div);
};
socket.onclose = function(event) {
alert("连接已关闭");
};
socket.onerror = function(event) {
alert("连接出错");
};
}
function logout() {
socket.close();
document.getElementById("chat").style.display = "none";
}
function send() {
var message = document.getElementById("message").value;
if (message == "") {
alert("请输入消息");
return;
}
document.getElementById("message").value = "";
var data = {
username: username,
message: message
};
socket.send(JSON.stringify(data));
}
</script>
</body>
</html>
```
阅读全文