bat*_*roz 1 design-patterns module node.js express socket.io
目前我正在开发一个使用 websockets 进行通信的节点服务器。我习惯于在我的应用程序中应用 MVC(或 MC)模式。我想以类似的方式构建我的 socket.io,我的问题是如何以最好的方式做到这一点?
现在我有这样的事情:
实用程序/socket.ts:
type IO = null | SocketIO.Server;
let io: IO;
export function init(ioServer: IO) {
io = ioServer;
}
export function getIO(): IO {
return io;
}
Run Code Online (Sandbox Code Playgroud)
应用程序:
import express from 'express';
...
import { init } from './utils/socket';
import startSockets from './controllers';
const app = express();
...
const server = app.listen(process.env.PORT || 5000);
const io = socketio.listen(server);
if (io) {
init(io);
io.on('connect', startSockets);
}
Run Code Online (Sandbox Code Playgroud)
控制器/index.ts:
import { onConnect } from './connect';
import { getIO } from '../utils/socket';
export default function (socket: SocketIO.Socket) {
const io = getIO();
socket.on('connect-player', onConnect);
}
Run Code Online (Sandbox Code Playgroud)
控制器/connect.ts:
import Player from '../models/Player';
export const onConnect = async function (this: SocketIO.Socket, name: string) {
const player = await Player.create({ name });
this.broadcast.emit('player-connected', `Player ${name} joined the game!`);
this.emit(
'player-connected',
`Congratulations ${name}, you successfully joined our game!`,
player,
);
this.on('disconnect', onDisconnect.bind(this, player.id));
};
const onDisconnect = async function (this: SocketIO.Socket, playerId: string) {
const player = await Player.findById(playerId);
await player?.remove();
this.broadcast.emit(
'player-connected',
`Player ${player?.name} left our game!`,
);
};
Run Code Online (Sandbox Code Playgroud)
我不确定是否在我的控制器中使用“this”以及 utils/socket.ts 中的单例模式。这样合适吗?对我来说最重要的是保持应用程序的清晰和可扩展。
我正在使用快递和打字稿。Player.ts 是我的玩家的 Moongoose 模式。
小智 5
我一直在用 socket.io + express.js 苦苦挣扎,特别是我也习惯于应用 MVC 模式。
在搜索、谷歌搜索和堆栈溢出时,这些链接帮助我完成了项目。
https://blueanana.github.io/2017/03/18/Socket-io-Express-4/
https://github.com/onedesign/express-socketio-tutorial
https://gist.github.com/laterbreh /5d7bdf03258152c95b8d
在 Express 4 和 express-generator 的 /bin/www 中使用 socket.io
我不会说什么是最好的方式,我什至不喜欢这种表达方式。但我会说这是一种方式,它有助于保持清晰、可扩展、有条理和模块化。
特别是每个项目都有自己的内在要求和需求。
希望这些可以像对我一样帮助您,让您了解和了解项目需要如何完成以及需要做什么。
| 归档时间: |
|
| 查看次数: |
2388 次 |
| 最近记录: |