我在我的網頁后端使用 Express Typescript。
我已經定義了網路套接字socket.io:
/src/index.ts:
const initializeExpress = (): void => {
const app = express();
let http = require("http").Server(app);
let io = require("socket.io")(http, {
cors: {}
});
const socket_ids = {};
io.on("connection", function(socket: any) {
console.log("a user connected. socket.id: ", socket.id, "socket.username: ", socket.username);
socket_ids[socket.username] = socket.id;
});
const server = http.listen(3001, function() {
console.log("listening on *:3001");
});
// register middleware
io.use((socket, next) => {
socket.username = socket.handshake.auth.username;
socket.organization = socket.handshake.auth.organization;
next();
});
// sends each client something constantly
setInterval(() => {
for (const u in socket_ids){
const my_socket = io.sockets.sockets.get(socket_ids[u]);
my_socket.emit("knock", "knock-knock");
}
}, 10000);
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'build')));
app.use(addRespondToResponse);
attachPublicRoutes(app);
};
initializeExpress();
當后端啟動時,我可以確認套接字正在作業,因為我可以接收knock-knock我的代碼發送到每個客戶端套接字的訊息。
現在,在許多其他檔案中,我需要socket.emit()根據業務邏輯對不同地方的特定客戶進行處理。所以我需要做my_socket = io.sockets.sockets.get(socket_ids[u])。
如何全域維護socket_ids物件和io物件/全域訪問它?
uj5u.com熱心網友回復:
您可以在一個類中定義一個全域狀態管理器(它基本上只是一個帶有 get 和 set 方法的簡單 javascript 物件),該類可以從任何腳本匯入和訪問。然后將這些變數附加到該狀態。
這是一個非常簡單但可行的版本:
export class StateManager {
static addToState = (key, value) => {
if (!StateManager._singleton) {
StateManager._singleton = new StateManager();
}
StateManager._singleton.addToState(key, value);
};
static readFromState = (key: string) => {
if (!StateManager._singleton) {
StateManager._singleton = new StateManager();
}
return StateManager._singleton.readFromState(key);
};
private static _singleton: StateManager;
private _state: Record<string, any>;
private constructor() {
this._state = {};
}
private addToState = (key, value) => (this._state[key] = value);
private readFromState = (key) => this._state[key];
}
為了使用,您可以將其添加到您的代碼中:
import { StateManager } from './state';
// your code where socket_id and io are set
StateManager.addToState('socket_ids', socket_id);
StateManager.addToState('io', io);
// your code where you want to retrieve the values:
const socket_ids = StateManager.readFromState('socket_ids');
請參閱Stackblitz上的作業示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/313431.html
