怎么使用springboot实现在线聊天
时间: 2023-10-30 07:09:07 浏览: 100
要使用Spring Boot实现在线聊天,可以遵循以下步骤:
1.创建一个Spring Boot项目,添加必要的依赖项(如Web,WebSocket)。
2.创建一个WebSocket配置类,其中包括一个WebSocket处理程序和一个消息代理。
3.创建一个聊天控制器类,其中包括处理WebSocket连接和发送消息的方法。
4.创建一个聊天界面,可以使用HTML,JavaScript和CSS等前端技术来实现。
5.将聊天界面和聊天控制器类连接起来,以便在浏览器中发送和接收消息。
6.测试聊天功能,打开多个浏览器窗口并尝试在它们之间发送消息。
以下是一个简单的示例代码:
WebSocket配置类:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").withSockJS();
}
}
聊天控制器类:
@Controller
public class ChatController {
@MessageMapping("/chat")
@SendTo("/topic/messages")
public Message sendMessage(Message message) {
return message;
}
}
聊天界面:
<html>
<head>
<title>Spring Boot Chat</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@splidejs/splide@3.0.7/dist/js/splide.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@splidejs/splide@3.0.7/dist/css/splide.min.css">
<script src="https://cdn.jsdelivr.net/npm/@splidejs/splide@3.0.7/dist/js/splide.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-OgVRvuATP1z7JjHLkuOUzXw704I+aYI3q5f8MkYUwOgtxlV0rbU+6XuX7jIweIX"
crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-OgVRvuATP1z7JjHLkuOUzXw704I+aYI3q5f8MkYUwOgtxlV0rbU+6XuX7jIweIX"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"
integrity="sha512-9X9B1vM0jZt1O2Q3qAERj+Irr8xWxHYZRZp9Y9DdLZ8OeWOrRf+6ApBn6F5U6b5J+1Q2q3z4Zm+oJ8mGwPBUw=="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.0/sockjs.min.js"
integrity="sha512-XVz2Kj4Yq3+0ZdOaZVwJwP5zjKQup1eB+7xu9J0Xz7gJvEjg0GZwJf/1g1+TtgcJnK8Hn0P+ycYgNvQ1aZSDbw=="
crossorigin="anonymous"></script>
<script src="chat.js"></script>
</head>
<body>
<div class="container">
<h1>Spring Boot Chat</h1>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="message">Message:</label>
<input type="text" class="form-control" id="message">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="splide">
<div class="splide__track">
<div class="splide__list" id="messages">
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
chat.js文件:
$(function () {
var stompClient = null;
function connect() {
var socket = new SockJS('/chat');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/messages', function (message) {
showMessage(JSON.parse(message.body));
});
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
console.log("Disconnected");
}
function sendMessage() {
var name = $("#name").val();
var message = $("#message").val();
stompClient.send("/app/chat", {}, JSON.stringify({name: name, message: message}));
}
function showMessage(message) {
var html = '<div class="media"><div class="media-body"><h5 class="mt-0">' + message.name + '</h5>' + message.message + '</div></div>';
$("#messages").append(html);
var splide = new Splide('.splide', {
type: 'loop',
perPage: 5,
perMove: 1,
gap: '1em',
pagination: false,
arrows: false,
autoplay: true,
pauseOnHover: false,
interval: 3000,
speed: 1000,
}).mount();
}
$("form").on('submit', function (e) {
e.preventDefault();
});
$("#connect").click(function () {
connect();
});
$("#disconnect").click(function () {
disconnect();
});
$("#send").click(function () {
sendMessage();
$("#message").val("");
});
});
Message类:
public class Message {
private String name;
private String message;
public Message() {
}
public Message(String name, String message) {
this.name = name;
this.message = message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
阅读全文