• ​​1.依赖​​
  • ​​2.websocket配置:​​
  • ​​3.前端​​
  • ​​4.注意事项​​

效果:

springboot整合websocket实现群聊_websocket


也可以打开新窗口连接一个新用户发消息

springboot整合websocket实现群聊_java_02

1.依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</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>2.1.4</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>sockjs-client</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>

</dependency>

除了第一个之外其他的都是前端的依赖包

2.websocket配置:

springboot整合websocket实现群聊_websocket_03

@Component

public class WebSocketBean {
private Session session;
}
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry)
{
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/socket");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry){
registry.addEndpoint("/chat").withSockJS();
}

}
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Message greeting(Message message){
return message;
}
// ,@MessageMapping("/hello")注解的方法将用来接收
// “/app/hello”路径发送来的消息,在注解方法中对消息进行处理后,
// 再将消息转发到@SendTo定义的路径上,
// 而@SendTo路径是一个前缀为“/topic”的路径,
// 因此该消息将被交给消息代理broker,再由broker进行广播。


}
@Data
public class Message {
private String name;

private String title;
private String content;
}

3.前端

<!DOCTYPE html>
<html lang="en">
<head>
<title>群聊</title>
<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>
<script src = "/app.js"></script>
</head>

<body>
<div>
<label for="name">用户名:</label>
<input type="text" id="name" placeholder="用户名">
</div>
<div>
<label for="title">标题:</label>
<input type="text" id="title" placeholder="标题">
</div>
<div>
<button id="connect" type="button">连接</button>
<button id="disconnect" type="button" disabled="disabled">断开</button>
</div>
<label for="name">请输入聊天内容:</label>
<input type="text" id="content" placeholder="聊天内容">
<button id="send" type="button">发送</button>
<div id="greetings">
<div id="conversation" style="display: none">群聊中</div>
</div>
</body>
</html>

app.js:

var stompClient = null
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
$("#chat").show();
} else {
$("#conversation").hide();
$("#chat").hide();
}
$("#greetings").html("")
}
function connect(){
if (!$("#name"). val()) {
return;
}
var socket =new SockJS('/chat');
stompClient =Stomp.over(socket);
stompClient.connect({}, function (frame){
setConnected(true);
stompClient. subscribe ('/topic/greetings', function (greeting){
showGreeting (JSON. parse (greeting. body));
})
})
}
function disconnect(){
if (stompClient != null) {
stompClient.disconnect();}
setConnected(false);
}
function sendName() {
stompClient.send("/socket/hello", {},
JSON.stringify({'name': $("#name").val(), 'title':$("#title").val(),'content': $("#content").val()}));
}
function showGreeting(message) {
$("#greetings")
.append("<div>" + message.name + ": " + message.content +":"+ message.title+ "</div>");
}
$(function (){
$("#connect" ).click(function() { connect(); })
$("#disconnect" ).click(function() { disconnect(); })
$("#send").click(function (){ sendName () })
});

首先使用SockJS建立连接,然后创建一个STOMP实例发起连接请求,在连接成功的回调方法中,首先调用setConnected(true);方法进行页面的设置,然后调用STOMP中的subscribe方法订阅服务端发送回来的消息,并将服务端发送来的消息展示出来(使用showGreeting方法)。

4.注意事项

message一定要有get 和set方法,且属性名要与前端的一一对应
关于前后端中的路径:

  1. registry.addEndpoint("/chat").withSockJS();
    定义一个前缀为/chat的endPoint,并开启sockjs支持,客户端通过这里配置的URL来建立websocket连接

    var socket =new SockJS(’/chat’);
  2. registry.enableSimpleBroker("/topic");
    设置消息代理的前缀,如果消息的前缀是/topic就会转发给消息代理
    @SendTo("/topic/greetings") 将消息转发到sento对应的路径上
    前端js:
    stompClient. subscribe (’/topic/greetings’, function (greeting){
    showGreeting (JSON. parse (greeting. body));
    })
  3. @MessageMapping("/hello")
    用来接收/socket/hello路径发过来的消息,然后再转发到@SendTo定义的路径上
function sendName() {
stompClient.send("/socket/hello", {},
JSON.stringify({'name': $("#name").val(), 'title':$("#title").val(),'content': $("#content").val()}));
}