SpringBoot+WebSocket实现多人在线聊天案例
1.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl</groupId>
<artifactId>chat01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>chat01</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--前端库依赖-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>sockjs-client</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>stomp-websocket</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
<!-- <version>0.48</version>-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.消息实体类
package com.yl.chat01.domain;
import java.io.Serializable;
public class Message implements Serializable {
private String name;
private String content;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "Message{" +
"name='" + name + '\'' +
", content='" + content + '\'' +
'}';
}
}
3.controller
package com.yl.chat01.controller;
import com.yl.chat01.domain.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Message greeting(Message message) {
return message;
}
}
4.WebSocket的配置文件
package com.yl.chat01.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
}
}
5.前端发送消息页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/webjars/jquery/jquery.min.js"></script>
<script src="/webjars/sockjs-client/sockjs.min.js"></script>
<script src="/webjars/stomp-websocket/stomp.min.js"></script>
</head>
<body>
<div>
<label for="username">请输入用户名:</label>
<input type="text" id = "username" placeholder="用户名"/>
</div>
<div>
<input type="button" value="连接" id="connect"/>
<input type="button" value="断开连接" id="disconnect" disabled="disabled"/>
</div>
<div id="chat"></div>
<div>
<label for="content">请输入聊天内容</label>
<input type="text" id="content" placeholder="聊天内容"/>
</div>
<input type="button" value="发送" disabled="disabled" id="send"/>
<script>
var stompClient;
$(function () {
$("#connect").click(function () {
connect()
})
$("#send").click(function () {
stompClient.send("/hello",{},JSON.stringify({'name':$('#username').val(),'content':$("#content").val()}))
})
$("#disconnect").cilck(function () {
stompClient.disconnect();
disableButton(false);
})
})
function connect() {
if (!$("#username").val()) {
alert("请输入用户名")
return;
}
var socketjs = new SockJS("/chat");
stompClient = Stomp.over(socketjs);
stompClient.connect({},function (frame) {
alert("connect success")
disableButton(true);
stompClient.subscribe("/topic/greetings",function (obj) {
var msg = JSON.parse(obj.body);
$("#chat").append("<div>"+msg.name+ ":" + msg.content+"</div>")
})
})
}
function disableButton(connected) {
$("#connect").prop("disabled",connected);
$("#disconnect").prop("disabled",!connected);
$("#send").prop("disabled",!connected);
}
</script>
</body>
</html>
6.测试
6.1.客户端A
6.2.客户端B