【问题标题】:NodeJS, Express, Sockets.io: Cannot get .on("connection"... to fire on serverNodeJS、Express、Sockets.io:无法在服务器上触发 .on("connection"...
【发布时间】:2015-11-16 20:02:47
【问题描述】:

我正在尝试将 sockets.io 集成到我的 express 应用程序中。我使用 express 生成器来格式化我的应用程序,所以我必须在 bin/www 中设置我的 websocket。我发现了一个类似的问题,并应用了找到的答案here,指示我在 app.js 中创建我的套接字对象,将其附加到 app 对象,并通过 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 中的 websockets 实现是否有问题,这会破坏我的 websockets 服务器?我无法想象为什么这不起作用,因为在 app.js 中创建的对象已成功传递给 bin/www。在 bin/www 的末尾放置一个 console.log 会显示以下内容:

{ 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] } } }

【问题讨论】:

    标签: javascript node.js express websocket socket.io


    【解决方案1】:

    尝试从您创建的 app.io.sockets.on 中删除套接字 app.io = io() 。所以 io.sockets 不是一个函数,但 io.on('connection', function(){}) 是。看起来它是一个错字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多