1.引入jar
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2 开启websocket
@Configuration
public class DateConverConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3,配置类
@ServerEndpoint(value = "/bigscreen/websocket")
@Component
public class WebSocketServer {
private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
static List<Session> list =new ArrayList<Session>();
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
private static Map<String, WebSocketServer> map = new ConcurrentHashMap<>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
@OnOpen
public void onOpen(Session session) {
list.add(session);
this.session = session;
webSocketSet.add(this); //加入set中
//addOnlineCount(); //在线数加1
log.info("有新连接加入!");
/* try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}*/
}
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
webSocketSet.remove(this);
error.printStackTrace();
}
@OnClose
public void onClose() {
boolean remove = webSocketSet.remove(this);
log.info(remove + " 执行关闭方法 设置为离线");
}
/**
* 主动发送消息
*
* @param message
* @throws IOException
*/
public synchronized void sendMessage(String message) throws IOException {
if (this.session.isOpen()) {
synchronized (this.session) {
if (this.session.isOpen()) {
this.session.getBasicRemote().sendText(message);
}
}
}
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println(session.getId()+":"+message);
if(list.size()>1){
for (int i = 0; i < list.size(); i++) {
if(!list.get(i).getId().equals(session.getId())){
try {
list.get(i).getBasicRemote().sendText(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
/**
* 群发自定义消息
*/
public static void sendInfo(String message) throws IOException {
log.info(message);
for (WebSocketServer item : webSocketSet) {
try {
if (item.session.isOpen()) {
synchronized (item.session) {
if (item.session.isOpen()) {
item.sendMessage(message);
}
}
} else {
webSocketSet.remove(item);
}
} catch (IOException e) {
e.printStackTrace();
webSocketSet.remove(item);
continue;
}
}
}
}
4.调用方法
5.前端
$(function() {
if("WebSocket" in window){
// websocket = new WebSocket("ws://localhost:8088/websocket");
console.log("websocket 建立连接")
}else{
alert("请使用谷歌或360浏览器!");
}
websocket.onopen = function () {
console.log("数据发送中");
}
websocket.onerror = function () {
console.log("websocke连接异常!");
}
//连接关闭的回调方法
websocket.onclose = function () {
console.log("webSocket已关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭WebSocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
websocket.close();
}
// 20秒后开始接数据,防止查库操作没完成先执行了此方法
websocket.onmessage = function (e) {
webSocketData = JSON.parse(e.data);
if (webSocketData.equipmentCode){
// 没数据
oneData == null;
siteCurrentData = getCurrentData2(webSocketData);
} else {
// 有数据,刷新右侧曲线图
if (webSocketData.siteId==siteidTree){
options.xAxis.data.push(formatTimestamp(webSocketData.dataTime));
options.series[0].data.push(webSocketData.ois);
options.series[1].data.push(webSocketData.pmx);
options.series[2].data.push(webSocketData.voc);
var myChart = echarts.init(document.getElementById("polImg"));
myChart.setOption(options);
}
newDataOne = null;
oneData == null;
siteCurrentData = getCurrentData(webSocketData);
}
}
})