我的app.js
文件看起来像
let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let dotEnv = require('dotenv');
let helmet = require('helmet');
let compression = require('compression');
let passport = require('passport');
let socket_io = require("socket.io");
let app = express();
let io = socket_io();
app.io = io;
require('./server/config/socket')(io);
let useragent = require('express-useragent');
let cors = require('cors');
dotEnv.load();
require('./server/authentication/passport.local');
app.set('views', path.join(__dirname, 'server/views'));
app.set('view engine', 'jade');
app.set('view engine', 'ejs');
app.use(cors());
//app.use(logger('dev'));
app.use(helmet());
app.use(useragent.express());
app.use(compression())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(passport.initialize());
app.use(express.static(path.join(__dirname, 'public')));
/**
* Custom middle ware functions
*/
require('./server/middleware/authentication-middleware')(app);
require('./server/config/database')(app, process.env.NODE_ENV);
require('./server/routes')(app);
require('./server/middleware/custom-middleware')(app);
module.exports = app;
www
档案
let server = http.createServer(app);
let io = app.io;
io.attach(server);
socket.is
档案
module.exports = function(io) {
io.on('connection', function(socket) {
console.log('Socket.io is connected');
});
}
我尝试了很多方法,但它没有触发连接消息。这里有人帮我解决了什么问题吗?
package.json
档案
expressjs: 4.16.0
socket.io: 2.0.4
与此同时,我尝试过其他一些指令,但不起作用:https://onedesigncompany.com/news/express-generator-and-socket-io
提前致谢
答案 0 :(得分:2)
在客户端,您可以使用socket.io-client
let socket = ClientSocket({ transports: ['websocket'] });
socket.on('connection',()=>{
console.log("")
})
然后在服务器上(考虑到你有服务器实例。)
var socketIo = require("socket.io");
var io = socketIo.listen(server.listener);
io.on('connection', function (socketInstance) {
console.log("connected to server");
})
答案 1 :(得分:0)
您可能需要将io
传递给您的路线以使其可用:
require('./server/routes')(app, io);
或使用Express Router:
const yourSpecificRoute = require('./server/youRoutes)(io);
const router = express.Router();
router.use('/route', yourSpecificRoute);