首页 > 解决方案 > 构建 Node.js 和 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;
}

应用程序.ts:

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);
}

控制器/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);
}

控制器/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!`,
  );
};

我不确定在我的控制器中使用“this”以及在 utils/socket.ts 中使用单例模式。这合适吗?对我来说最重要的是保持应用程序清晰和可扩展。

我正在使用快递和打字稿。Player.ts 是我的月鹅模式的玩家。

标签: node.jsexpressdesign-patternsmodulesocket.io

解决方案


前段时间我一直在为 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

我不会说什么是最好的方式,我什至不喜欢这种表达方式。但我会说这是一种方式,它有助于保持清晰、可扩展、有条理并且非常模块化。
特别是每个项目都有自己的内在要求和需求。
希望这些能够像它为我所做的那样对您有所帮助,让您感受和理解在项目中需要如何以及需要做什么。


推荐阅读