导入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
在WebConfig中添加以下配置【若是使用内置tomcat】
@Bean
public ServerEndpointExporter createServerEndExporter() {
return new ServerEndpointExporter();
}
具体实现类
import com.alibaba.fastjson.JSONObject;
import com.framework.common.utils.DateUtils;
import com.framework.common.utils.RedisUtils;
import com.framework.common.utils.SpringContextUtils;
import com.framework.common.utils.StringUtil;
import com.framework.common.websocket.EpidemicData;
import com.framework.common.websocket.EpidemicWebSocketClient;
import com.framework.common.websocket.WebSocketMsg;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint("/websocket/epidemic")
@Component
public class EpidemicController {
public static final Logger logger = LoggerFactory.getLogger(EpidemicController.class);
@Autowired
private RedisUtils redisUtils;
private static CopyOnWriteArraySet<EpidemicController> user = new CopyOnWriteArraySet<EpidemicController>();
private Session session;
private Integer entId;
@OnOpen
public void onOpen(Session session) {
this.session = session;
user.add(this);
}
@OnClose
public void onClose(@PathParam("pageCode") String pageCode,Session session) {
user.remove(this);
}
public static void sendAllClients(String jsonMsg, int entId){
if(StringUtil.isBlank(jsonMsg)){
return;
}
try{
for(EpidemicController webSocket : user) {
if (webSocket.getEntId() == entId) {
webSocket.session.getBasicRemote().sendText(jsonMsg);
}
}
}catch (Exception e){
logger.error("向"+entId+"企业发送通行信息异常:"+e.getMessage());
e.printStackTrace();
}
}
@OnMessage
public void onMessage(String message, Session session) {
try {
if(StringUtil.isBlank(message)){
return;
}
WebSocketMsg webSocketMsg = new Gson().fromJson(message, WebSocketMsg.class);
String jsonMsg = webSocketMsg.getJsonMsg();
this.entId = webSocketMsg.getEntId();
for(EpidemicController webSocket : user){
if(webSocket.getSession().getId() == this.session.getId()){
webSocket.session.getBasicRemote().sendText(jsonMsg);
}
}
} catch (IOException e) {
logger.error("后台异常", e);
e.printStackTrace();
}
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public Session getSession() {
return session;
}
public Integer getEntId() {
return entId;
}
}
相应的js
websocketService() {
var that = this;
var websocket = null;
if ("WebSocket" in window) {
websocket = new WebSocket(
"ws://127.0.0.1:80/websocket/epidemic"
);
} else {
alert("当前浏览器不支持websocket");
}
function send() {
var msg = '{"entId": "'+ that.entId + '","jsonMsg": ""}';
try {
websocket.send(msg);
} catch (err) {
var tryTime = 0;
if (tryTime < 1) {
var t1 = setTimeout(function() {
tryTime++;
websocket.send(msg);
}, 3 * 1000);
} else {
console.error("重连失败.");
}
}
}
websocket.onmessage = function(event) {
};
websocket.onopen = function() {
console.log("websocket连接成功----")
};
websocket.onclose = function() {
};
websocket.onerror = function() {
console.log("websocket连接错误...");
};
window.onbeforeunload = function() {
};
function closeWebSocket() {
}
$(function() {
send();
});
},