我有app.js文件:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var mongojs = require('mongojs');
var db = mongojs("mongodb://USER:PASS@SERVER:PORT/DB", []);
var ObjectId = require('mongodb').ObjectID;
var CronJob = require('cron').CronJob;
var request = require('request');
var fcm = require('./routes/fcm');
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(express.static(__dirname + '/src'));
require('./routes/sockets')(app, io, mongojs, db, ObjectId, CronJob, request, fcm);
require('./routes/userServer')(app, io, mongojs, db, ObjectId, CronJob, request, fcm);
require('./routes/ridesServer')(app, io, mongojs, db, ObjectId, CronJob, request);
require('./routes/offersServer')(app, io, mongojs, db, ObjectId, CronJob, request);
require('./routes/notificationsServer')(app, io, mongojs, db, ObjectId, CronJob, request);
server.listen("8080", function() {
console.log("Connected to db and listening on port 8080");
});
如您所见,我在app.js文件中定义主要模块,然后将其作为“依赖关系”传输到每个路径页面。
因为我有/routes/sockets.js页面,我认为将socket.io连接放在那里并处理从客户端发出的每个动作都是明智的,如下所示:
/routes/sockets.js文件:
module.exports = function(app, io, mongojs, db, ObjectId, CronJob, request) {
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on("To server", function(data) {
console.log(data);
});
});
};
有(routes / sockets.js)我可以像这样处理来自客户端的操作:
socket.emit("To server", "The Data");
这是一个正确的放置位置吗? 我做得好还是应该纠正?
感谢。
答案 0 :(得分:0)
我通常使用一个函数创建一个新文件,该函数接受 io
对象并吐出所有 socket
指令,就像这样
我的示例应用程序/服务器/index.js
const express = require("express");
const cors = require("cors");
const http = require("http");
const socketio = require("socket.io");
const PORT = process.env.PORT || 5000;
const app = express();
const socketHolder = require("./utils/sockets"); // this is the file I put my sockets in
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST", "PUT", "DELETE"],
allowedHeaders: "*",
},
});
const connectDB = require("./config/db");
socketHolder(io);
// Database connection
connectDB()
// ... additional router stuff
我的socketHolder util 文件
// All requires at the top of the file
const socketHolder = (io) =>
io.on("connection", (socket) => {
socket.on("doSomething", () => {
console.log("Do something")
})
// ...etc
})