NodeJS、Express、Sockets.io:无法在服务器上启动.on(“connection”

NodeJS, Express, Sockets.io: Cannot get .on("connection"... to fire on server

本文关键字:on 启动 connection 服务器 Sockets Express io NodeJS      更新时间:2023-09-26

我正在尝试将sockets.io集成到我的express应用程序中。我使用express生成器来格式化我的应用程序,所以我必须在bin/w中设置我的websocket。我发现了一个类似的问题,并应用了这里的答案,指示我在app.js中创建套接字对象,将其附加到应用程序对象,并通过bin/www中的导出访问它,将其连接到服务器。

这是我当前的app.js文件:

var express = require('express'),
    path = require('path'),
    favicon = require('serve-favicon'),
    bodyParser = require('body-parser'),
    sanitizer = require('sanitizer'),
    socket_io = require('socket.io'),
    config = require('./lib/config'),
    db = require('./lib/db'),
    fs = require('fs'),
    app = express(),
    io = socket_io();
app.io = io;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(bodyParser.json({strict: false}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req,res,next){
    req.io = io;
    next();
});
app.io.sockets.on('connection', function(socket){
    console.log('connected!');
});
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.json({
        code: err.status,
        err: err.message
    }).end();
});
module.exports = app;

这是我的bin/www文件,关于socket.io和http服务器:

var app = require('../app');
var debug = require('debug')('fresco:server');
var http = require('http');
/**
 * Get port from environment and store in Express.
 */
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
 * Create HTTP server.
 */
var server = http.createServer(app);
/**
 * Socket.io
 */
app.io.attach(server);
/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port);

我试图通过ws://localhost:3000/访问本地运行的服务器,但在客户端上没有得到响应。我在express中的websocket实现是否出错,导致我的websockets服务器崩溃?我无法想象为什么这不起作用,因为在app.js中创建的对象正被成功地传递到bin/w。将console.log放在bin/www的末尾显示以下内容:

{ nsps:
{ '/':
  { name: '/',
    server: [Circular],
    sockets: [],
    connected: {},
    fns: [],
    ids: 0,
    acks: {},
    adapter: [Object],
    _events: [Object] } },
_path: '/socket.io',
_serveClient: true,
_adapter: [Function: Adapter],
_origins: '*:*',
sockets:
{ name: '/',
 server: [Circular],
 sockets: [],
 connected: {},
 fns: [],
 ids: 0,
 acks: {},
 adapter: { nsp: [Circular], rooms: {}, sids: {}, encoder: {} },
 _events: { connection: [Function] } },
eio:
{ clients: {},
 clientsCount: 0,
 pingTimeout: 60000,
 pingInterval: 25000,
 upgradeTimeout: 10000,
 maxHttpBufferSize: 100000000,
 transports: [ 'polling', 'websocket' ],
 allowUpgrades: true,
 allowRequest: [Function],
 cookie: 'io',
 ws:
  { domain: null,
    _events: {},
    _maxListeners: undefined,
    options: [Object],
    path: null,
    clients: [] },
 _events: { connection: [Function] } },
 httpServer:
 { domain: null,
 _events:
  { connection: [Function: connectionListener],
    clientError: [Function],
    close: [Function],
    upgrade: [Function],
    request: [Function],
    error: [Function: onError],
    listening: [Function: onListening] },
 _maxListeners: undefined,
 _connections: 0,
 _handle:
  { fd: undefined,
    reading: false,
    owner: [Circular],
    onread: null,
    onconnection: [Function: onconnection],
    writeQueueSize: 0 },
 _usingSlaves: false,
 _slaves: [],
 allowHalfOpen: true,
 pauseOnConnect: false,
 httpAllowHalfOpen: false,
 timeout: 120000,
 _connectionKey: '4:null:3000' },
 engine:
 { clients: {},
 clientsCount: 0,
 pingTimeout: 60000,
 pingInterval: 25000,
 upgradeTimeout: 10000,
 maxHttpBufferSize: 100000000,
 transports: [ 'polling', 'websocket' ],
 allowUpgrades: true,
 allowRequest: [Function],
 cookie: 'io',
 ws:
  { domain: null,
    _events: {},
    _maxListeners: undefined,
    options: [Object],
    path: null,
    clients: [] },
 _events: { connection: [Function] } } }

尝试从制作app.io = io()app.io.sockets.on中移除套接字。io.sockets不是一个函数,但io.on('connection', function(){})是。看起来这是一个拼写错误。