1.java后端的maven添加websocket依赖
<!-- websocket依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.实例化ServerEndpointExporter对象,
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
3.创建一个类,该类的功能是提供websocket服务
注意:这里填写的map的key是uuid变量,不是"uuid" websocket_map.get(uuid);
@Component
@ServerEndpoint("/ws/login/{uuid}")
public class LoginWebSocket {
private Session session;
private static final ConcurrentMap<String,LoginWebSocket> websocket_map = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(@PathParam("uuid") String uuid, Session session) {
this.session = session;
websocket_map.put(uuid,this);
System.out.println("有新连接加入!当前在线人数为" + websocket_map.size());
}
@OnClose
public void onClose(@PathParam("uuid") String uuid,Session session) throws IOException {
websocket_map.remove(uuid);
session.close();
System.out.println("有一连接关闭!当前在线人数为" + websocket_map.size());
}
//发送消息
@OnMessage
public void onMessage(Session session,String message) throws IOException {
String uuid = generateUUID();
session.getBasicRemote()
.sendText(uuid);
}
//产生uuid
private String generateUUID(){
UUID uuid = UUID.randomUUID();
return uuid.toString();
}
private void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public static void sendMessage(String uuid,String message) throws IOException {
LoginWebSocket qrcodeWebsocket = websocket_map.get(uuid);
if(qrcodeWebsocket != null){
qrcodeWebsocket.sendMessage(message);
}
}
}
接下来需要控制器进行页面的跳转
@Controller
public class LoginController {
@GetMapping("/")
public String loginPage(){
return "login";
}
@GetMapping("/generateUUID")
@ResponseBody
public String generateUUID(){
UUID uuid = UUID.randomUUID();
return uuid.toString();
}
@GetMapping("/confirmLogin/{uuid}")
public String confirmLoginPage(@PathVariable("uuid") String uuid, Model model){
model.addAttribute("uuid",uuid);
return "confirmLogin";
}
@GetMapping("/loginSuccess/{uuid}")
public String loginSuccess(@PathVariable("uuid") String uuid) throws IOException {
LoginWebSocket.sendMessage(uuid,"确认登录");
return "loginSuccess";
}
}
前端测试发起请求获取uuid,生成二维码,连接websocket
创建了一个登录html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
<link rel="stylesheet" href="bootstrap.css">
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-md-6 offset-md-3">
<div class="card">
<div class="card-body text-center" style="margin: 1px auto">
<div id="qrcode"></div>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs/qrcode.min.js"></script>
<script>
var qr = new QRCode(document.getElementById("qrcode"),{
text:"",
width:128,
height:128
})
//页面加载时,发起请求获取uuid
fetch("/generateUUID").then(response => response.text()).then(uuid => {
var confirmUrl = "http://" + window.location.host + "/confirmLogin/" + uuid
console.log("uuid",uuid);
qr.makeCode(confirmUrl);
//连接websocket
var socket = new WebSocket("ws://" + window.location.host + "/ws/login/" + uuid)
socket.onopen = function (event) {
console.log("websocket连接已经打开");
}
socket.onmessage = function (event) {
var message = event.data;
console.log(message);
if (message === "确认登录"){
window.location.href = "/loginSuccess/"+ uuid
}
}
socket.onclose = function (event) {
console.log("websocket连接已经关闭");
}
})
</script>
</html>
一个确认登录页面,注意这里由于使用了thymeleaf的th元素,需要引入约束空间xmlns:th=“http://www.thymeleaf.org”
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>确认页面</title>
<link rel="stylesheet" href="bootstrap.css">
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-md-6 offset-md-3">
<div class="card">
<div class="card-body text-center">
<h1>请确认登录</h1>
<form th:action="@{'/loginSuccess/'+${uuid}}">
<button id="confirmButton" class="btn btn-primary mt-3">确认登录</button>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
一个登录成功页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录成功</title>
<link rel="stylesheet" href="bootstrap.css">
</head>
<body>
后台界面
<a href="/" class="btn btn-primary mt-3">退出</a>
</body>
</html>
将bootstrap.css放在static文件下
将下面这个路径粘贴到浏览器获得bootstrap.css源码,在static文件下新建bootstrap.css文件,粘贴进去
https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css
运行结果:
浏览器输入http://192.168.xx.xx(自己的ip):8888/
文章来源:https://www.toymoban.com/news/detail-626417.html
手机扫码,出现确认登录按钮,点击确认登录,跳转到登录成功页面,同时PC端也跳转到登录成功页面。文章来源地址https://www.toymoban.com/news/detail-626417.html
到了这里,关于SpringBoot搭建WebSocket初始化的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!