前端代码
function initWebSocket() {
if (typeof WebSocket == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
var wsPathStr = wsPath + uuid;
console.log("uuid22:" + uuid);
socket = new WebSocket(wsPathStr);
socket.onopen = function () {
console.log("Socket 已打开");
socket.send("这是来自客户端的消息" + location.href + new Date());
};
socket.onmessage = function (msg) {
console.log(msg.data);
var data = JSON.parse(msg.data);
if (data.code == 200) {
alert("登录成功!");
window.sessionStorage.uuid = uuid;
window.sessionStorage.userId = data.userId;
window.sessionStorage.projId = data.projId;
window.location.href = "pages/upload.html";
} else {
debugger;
let path2 = getQrPath2 + "/" + uuid;
axios
.get(path2, {
params: { dd: "cc" },
})
.then(
function (success) {
console.log("成功");
},
function (fail) {
console.log("失败");
}
)
.catch(function (error) {
console.log("异常");
});
}
};
socket.onclose = function () {
console.log("Socket已关闭");
};
socket.onerror = function () {
alert("Socket发生了错误");
};
}
后端Java代码
package com.example.poi.utils;
import cn.hutool.json.JSONObject;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
static Log log= LogFactory.get(WebSocketServer.class);
private static int onlineCount = 0;
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
private Session session;
private String sid="";
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this);
addOnlineCount();
log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
this.sid=sid;
}
@OnClose
public void onClose() {
webSocketSet.remove(this);
subOnlineCount();
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自窗口"+sid+"的信息:"+message);
for (WebSocketServer item : webSocketSet) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","张三");
jsonObject.put("code",2001);
jsonObject.put("userId",16);
jsonObject.put("projId",200);
item.sendMessage(jsonObject.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
if(sid == null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
pom
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.13version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>5.7.10version>
dependency>
<dependency>
<groupId>com.google.zxinggroupId>
<artifactId>coreartifactId>
<version>3.4.1version>
dependency>
<dependency>
<groupId>commons-langgroupId>
<artifactId>commons-langartifactId>
<version>2.6version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-websocketartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.12version>
dependency>
生成二维码
@RequestMapping(value = "/getLoginQr" ,method = RequestMethod.GET)
public void createCodeImg(HttpServletRequest request, HttpServletResponse response){
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
try {
String uuid = "jdhasndi452iiwn11";
response.addHeader("uuid", uuid);
response.addHeader("Access-Control-Expose-Headers", "uuid");
response.addHeader("Access-Control-Allow-Origin", "*");
QrCodeUtil.generate(uuid, 300, 300, "jpg",response.getOutputStream());
System.out.println("**");
} catch (Exception e) {
e.printStackTrace();
}
}
扫码前端
<div id="qrImgDiv"></div>
function initQrImg() {
$("#qrImgDiv").empty();
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", getQrPath, true);
xmlhttp.responseType = "blob";
xmlhttp.onload = function () {
console.log(this);
uuid = this.getResponseHeader("uuid");
console.log("uuid=", uuid);
if (this.status == 200) {
var blob = this.response;
var img = document.createElement("img");
img.className = "qrCodeBox-img";
img.onload = function (e) {
window.URL.revokeObjectURL(img.src);
};
img.src = window.URL.createObjectURL(blob);
document.getElementById("qrImgDiv").appendChild(img);
}
};
xmlhttp.send();
}