1、依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2、使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div style="padding: 40px">
<font color="black" ><strong>账户登录测试</strong></font><br><br>
账号<input id="username" type="text"><br>
密码<input id="password" type="text"><br><br>
<input type="button" value="登录" >
<input type="button" value="注册" style="margin-left: 60px">
</div><br>
<div style="padding: 40px">
<font color="black" ><strong>扫码登录测试</strong></font><br><br>
<img src="${url}" style="width: 100px;height: 100px"/></a><br>
</div>
</body>
<script>
var token;
if( typeof(WebSocket) == "undefined"){
alert("您的浏览器不支持websocket")
}else {
alert("您的浏览器支持websocket")
socket = new WebSocket("ws://127.0.0.1/websocket/".replace("http","ws"));
socket.onopen = function () {
console.log("socket已打开")
socket.send("[[${code}]]")
};
socket.onmessage = function (msg){
token = JSON.parse(msg.data).data();
console.log("TOKEN获取成功",token);
};
socket.close =function (){
console.log("socket已关闭")
};
socket.onerror = function (){
console.log("socket发生了错误,请刷新")
}
}
</script>
</html>
@Component
@ServerEndpoint("/websocket/")
public class WebSocketServer {
static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
private static AtomicInteger onlineCount = new AtomicInteger(0);
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
private Session session;
private String code;
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this);
addOnlineCount();
log.info("有新请求链接进入,当前在线人数为" + getOnlineCount());
}
@OnClose
public void onClose(){
webSocketSet.remove(this);
subOnlineCount();
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
@OnMessage
public void onMessage(String message, Session session){
log.info("收到来自窗口的信息,Code为:" + message);
for (WebSocketServer item : webSocketSet) {
if(item.session == item.session){
item.code = message;
}
}
}
@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, String code){
log.info("推送消息到窗口" + code + ",推送内容:" + message);
for (WebSocketServer item : webSocketSet) {
try {
if(code == null){
item.sendMessage(message);
}else if(item.code == code){
item.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void subOnlineCount() {
WebSocketServer.onlineCount.decrementAndGet();
}
private static int getOnlineCount() {
return onlineCount.get();
}
public void addOnlineCount() {
WebSocketServer.onlineCount.incrementAndGet();
}
}
|