一、创建项目
二、添加依赖
此处添加的是前端的依赖,为得是方便管理文件,不用在引用大量的js文件。
Maven搜索网址
<!-- https://mvnrepository.com/artifact/org.webjars/sockjs-client -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>sockjs-client</artifactId>
<version>1.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.webjars/jquery -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.webjars/stomp-websocket -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>stomp-websocket</artifactId>
<version>2.3.3-1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.webjars/webjars-locator-core -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
</dependency>
三、添加配置类
package com.tony.websocket.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;
/**
* Created with IntelliJ IDEA.
*
* @Title: WebSocketConfig
* @Auther: 皮蛋布丁
* @Date: 2021/07/05/20:21
* @Description: 配置类
*/
@Configuration
@EnableWebSocketMessageBroker //开启websocket消息代理
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
/**
* @Description: configureMessageBroker 配置消息代理
* @Param: [registry]
* @return: void
* @Author: 皮蛋布丁
* @Date: 2021/7/5 20:25
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
//前缀为/topic的消息时,就将此消息转发给websocket代理,然后消息代理将消息转发给客户端
registry.enableSimpleBroker("/topic");
// 前缀为/app的消息,就被代理处理
// 配置一个或多个前缀,通过这些前缀过滤取要被具体的方法处理的消息
registry.setApplicationDestinationPrefixes("/app");
}
/**
* @Description: registerStompEndpoints 注册连接点
* @Param: [registry]
* @return: void
* @Author: 皮蛋布丁
* @Date: 2021/7/5 20:33
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("chat").withSockJS();
}
}
四、消息对象封装
package com.tony.websocket.bean;
/**
* Created with IntelliJ IDEA.
*
* @Title: Message
* @Auther: 皮蛋布丁
* @Date: 2021/07/05/20:37
* @Description: 消息对象
*/
public class Message {
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;
}
}
五、添加controller
方式1
package com.tony.websocket.controller;
import com.tony.websocket.bean.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
/**
* Created with IntelliJ IDEA.
*
* @Title: GreetingController
* @Auther: 皮蛋布丁
* @Date: 2021/07/05/20:35
* @Description:
*/
@Controller
public class GreetingController {
@MessageMapping("/hello") //greeting方法用来处理浏览器发送过来的消息,消息则往/hello这里发送
@SendTo("/topic/greetings") //消息在greeting方法中处理完成后,消息转发到/greetings
public Message greeting(Message message) {
return message;
}
}
方式2
package com.tony.websocket.controller;
import com.tony.websocket.bean.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
/**
* Created with IntelliJ IDEA.
*
* @Title: GreetingController
* @Auther: 皮蛋布丁
* @Date: 2021/07/05/20:35
* @Description:
*/
@Controller
public class GreetingController {
@Autowired
SimpMessagingTemplate simpMessagingTemplate; //消息发送模板
/**
* @Description: greeting 群聊的实现(方式2)
* @Param: [message]
* @return: void
* @Author: 皮蛋布丁
* @Date: 2021/7/5 22:07
*/
@MessageMapping("/hello")
public void greeting(Message message) {
simpMessagingTemplate.convertAndSend("/topic/greetings",message);
}
}
六、构建聊天界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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>
<table>
<tr>
<td>请输入用户名:</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td><input type="button" id="connect" value="连接"></td>
<!-- disabled="disabled":默认不可点击-->
<td><input type="button" id="disconnect" disabled="disabled" value="断开连接"></td>
</tr>
</table>
<!--聊天界面-->
<div id="chat" style="display: none">
<table>
<tr>
<td>请输入聊天内容</td>
<td><input type="text" id="content"></td>
<td><input type="button" id="send" value="发送"></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
<!-- 展示聊天内容-->
<div id="conversation">群聊进行中...</div>
</div>
<script>
<!-- 定义连接方法-->
$(function () {
//连接按钮事件
$("#connect").click(function () {
connect();
})
//断开连接按钮事件
$("#disconnect").click(function () {
if (stompClient != null) {
//断开连接
stompClient.disconnect();
}
//恢复按钮状态
setConnection(false);
})
//发送按钮点击事件
$("#send").click(function () {
//发送消息(参数1:发送地址;参数2:消息优先级;参数3:JSON消息对象)
stompClient.send('/app/hello',{},JSON.stringify({'name':$('#name').val(),'content':$('#content').val()}))
})
})
var stompClient = null;
function connect() {
//判断是否输入用户名
if (!$("#name").val()) {
return;
}
//建立连接
var socket = new SockJS('/chat');
stompClient = Stomp.over(socket);
//参数1:建立优先级;参数2:连接成功的回调;参数3:连接失败的回调
stompClient.connect({},function (success) {
//设置按钮状态
setConnection(true);
//订阅服务器上的消息
//参数1:服务器上的地址;参数2:服务器收到的消息
stompClient.subscribe('/topic/greetings',function (msg) {
showGreeting(JSON.parse(msg.body));
})
})
}
function setConnection(flag) {
//参数1:属性;参数2:设置状态
$("#connect").prop("disabled",flag);
$("#disconnect").prop("disabled",!flag);
//显示div
if (flag) {
$("#chat").show(); //显示
} else {
$("#chat").hide(); //隐藏
}
}
function showGreeting(msg) {
$("#conversation").append('<div>' + msg.name + ';' + msg.content + '</div>');
}
</script>
</body>
</html>
七、运行
1、建立连接
2、多用户聊天
在线聊天室的消息单聊的实现——springboot整合WebSocket(二)
注:能力有限,还请谅解,争取早日能够写出有质量的文章!
我是皮蛋布丁,一位爱吃皮蛋的热爱运动的废铁程序猿。