jcloud/dashboard/src2/socket.js

39 lines
1.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { io } from 'socket.io-client';
import { socketio_port } from '../../../../sites/common_site_config.json';
import { getCachedResource, getCachedListResource } from 'jingrow-ui';
export function initSocket() {
let host = window.location.hostname;
let siteName = window.site_name;
let protocol = window.location.protocol.slice(0, -1); // 移除末尾的 ':'
// 开发模式:使用 socketio_port有端口或明确是开发环境
// 生产模式:使用当前页面的协议和域名,不指定端口(通过 nginx 反向代理)
let port = '';
if (window.location.port) {
// 开发模式或有明确端口,使用 socketio_port
port = `:${socketio_port}`;
}
// 生产模式HTTPS 443 或 HTTP 80不指定端口使用当前页面的协议和域名
let url = `${protocol}://${host}${port}/${siteName}`;
let socket = io(url, {
withCredentials: true,
reconnectionAttempts: 5,
secure: protocol === 'https'
});
socket.on('refetch_resource', data => {
if (data.cache_key) {
let resource =
getCachedResource(data.cache_key) ||
getCachedListResource(data.cache_key);
if (resource) {
resource.reload();
}
}
});
return socket;
}