WebSocket用于在Web浏览器和服务器之间进行任意的双向数据传输的一种技术。WebSocket协议基于
TCP协议实现,包含初始的握手过程,以及后续的多次数据帧双向传输过程。其目的是在WebSocket应用和
WebSocket服务器进行频繁双向通信时,可以使服务器避免打开多个HTTP连接进行工作来节约资源,提高 了工作效率和资源利用率。
1.POM文件添加依赖包
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
2.后台webSocket 服务端点工具类
package com.zyf.test.util;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.fastjson.JSONObject;
import com.zyf.test.common.StringUtil;
@ServerEndpoint("/websocket/{username}")
public class WebSocketUtil {
private static int onlineCount = 0;
private static Map<String, WebSocketUtil> clients = new ConcurrentHashMap<String, WebSocketUtil>();
private Session session;
private String username;
@OnOpen
public void onOpen(@PathParam("username") String username, Session session) throws IOException {
this.username = username;
this.session = session;
addOnlineCount();
clients.put(username, this);
System.out.println(username+"已连接,当前连接数:"+getOnlineCount());
}
@OnClose
public void onClose() throws IOException {
clients.remove(username);
subOnlineCount();
}
@OnMessage
public void onMessage(String message) throws IOException {
if(StringUtil.isNotEmpty(message)){
JSONObject jsonTo = JSONObject.parseObject(message);
if (!jsonTo.get("To").equals("All")) {
sendMessageTo("给一个人", jsonTo.get("To").toString());
} else {
sendMessageAll("给所有人");
}
}
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessageTo(String message, String To) throws IOException {
for (WebSocketUtil item : clients.values()) {
String client = item.username.split("_")[0];
if (client.equals(To)){
item.session.getAsyncRemote().sendText(message);
System.out.println("已给用户["+item.username+"]发送信息完毕!");
}
}
}
public void sendMessageAll(String message) throws IOException {
for (WebSocketUtil item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketUtil.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketUtil.onlineCount--;
}
public static synchronized Map<String, WebSocketUtil> getClients() {
return clients;
}
}
3.具体业务中应用,此处根据自身业务使用
//业务代码,例如:前台发起二维码扫码实名认证请求,需要后台认证完成后主动推送消息给前台修改二维码状态
WebSocketUtil webSocketUtil = new WebSocketUtil();
String message = "";//此处是传递给前台的数据,可以是json串,方便前端解析
String to="张三";//此参数为前端要接收信息的用户
try {
webSocketUtil.sendMessageTo(message, to);
} catch (IOException e) {
e.printStackTrace();
logger.error("给前台用户发送信息失败,异常:{}",e);
}
//自己的业务处理代码
4.前端页面
var websocket = null;
//username 参数为客户端发起后台请求链接的用户
//初始链接之前二维码状态为未认证,
$("#verifyTs").html("未认证");
function verify(username) {
var protocol = window.location.protocol;
var webscoketProtocol="ws:";
if("https:"==protocol){
webscoketProtocol="wss:";
}
if('WebSocket' in window){
var url = webscoketProtocol+'//' + window.location.host + projectName+'/websocket/'+username;
websocket = new WebSocket(url); //打开WebSocket
}else{
alert("你的浏览器不支持WebSocket");
}
//连接发生错误的回调方法
websocket.onerror = function() {
alert("WebSocket连接发生错误,请稍后再试!");
console.log(username+"WebSocket连接发生错误,请稍后再试!");
};
websocket.onopen = function() {
console.log(username+"WebSocket连接成功");
// sock.send(JSON.stringify());//客户端发送消息
};
websocket.onmessage = function(e) {//接收消息
e = e || event;
var message = e.data;
console.log(username+"接收到消息:"+message);
//根据不同状态操作二维码
if(message!=null){
var verifyData=JSON.parse(message);
if(verifyData!=null){
var status=verifyData.statusCode;
if(status==1){
$("#verifyTs").html("认证通过");
$("#srrzQrCodeDiv").attr("style","display:none;");
applyFallBack();
}else if(status==2){
$("#verifyTs").html("认证未通过,原因:"+verifyData.auditConclusions);
}else if(status==0){
$("#verifyTs").html("认证中");
}else{
$("#verifyTs").html("未认证");
}
}
}
};
websocket.onclose = function() { //处理连接关闭事件
console.log(username+"WebSocket连接关闭");
};
window.onbeforeunload = function() {
websocket.close();
};
}