前端代码
function initWebSocket() {
if (typeof WebSocket == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//等同于socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20");
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) {
// debugger;
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 {
//如果过期了,关闭连接、重置连接、刷新二维码
// socket.close();
// initQrImg();
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;
/**
* @Author xu
* @create 2023/7/21 19
*/
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
static Log log= LogFactory.get(WebSocketServer.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//接收sid
private String sid="";
/**
* 连接建立成功调用的方法
*
* @param session
* @param sid
*/
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
this.sid=sid;
/*try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}*/
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
* 客户端发送过来的消息
* @param message
* @param session
*/
@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();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 实现服务器主动推送
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 发送消息
* @param message
* @param sid
* @throws IOException
*/
public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
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才能生效使用webSocketServer*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
注意如果在WebSocketServer 注入spring管理的容器问题,在WebSocketServer 类,自动注入Service层报错空指针异常,spring默认管理的都是单例(singleton),和 websocket (多对象)相冲突,项目启动时初始化,会初始化 websocket (非用户连接的),spring 同时会为其注入 service,该对象的 service 不是 null,被成功注入。但是,由于 spring 默认管理的是单例,所以只会注入一次 service。当新用户进入聊天时,系统又会创建一个新的 websocket 对象,这时矛盾出现了:spring 管理的都是单例,不会给第二个 websocket 对象注入 service,只要是用户连接创建的 websocket 对象,都不能再注入了。 controller,service ,dao 都是单例,所以注入时不会报 null。但是 websocket 不是单例,所以使用spring注入一次后,后面的对象就不会再注入了,会报null,在WebSocketServer 层注入如下成功:
/**static修饰,保证每一个WebSocketServer只有一个UserMapper实例*/
private static UserMapper userMapper;
@Autowired
public void setUserMapper(UserMapper userMapper) {
this.userMapper=userMapper;
}
pom
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.10</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
生成二维码
//获取登录二维码、放入Token
//@CrossOrigin
@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 {
//这里没啥操作 就是生成一个UUID插入 数据库的表里
//String uuid = userService.createQrImg();
String uuid = "jdhasndi452iiwn11";
response.addHeader("uuid", uuid);
response.addHeader("Access-Control-Expose-Headers", "uuid");
response.addHeader("Access-Control-Allow-Origin", "*");
// 这里是开源工具类 hutool里的QrCodeUtil
// 网址:http://hutool.mydoc.io/
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();
}
文章来源地址https://www.toymoban.com/news/detail-738035.html
文章来源:https://www.toymoban.com/news/detail-738035.html
到了这里,关于WebSocketServer的使用(@ServerEndpoint)(生成二维码)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!