socket.io不使用节点服务器

时间:2017-06-29 21:47:19

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

我尝试设置我的节点服务器,以实时更新所有连接的客户端和新信息。当我运行下面的代码时,io.sockets.on('connection')回调会不断被触发,使控制台充满消息Client connected!,并且前端未从socket.emit()更新。我做错了什么?

app.js

var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var models = require('./models.js');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;

// Connect to the Mongo database
mongoose.connect('mongodb://localhost/test');

仓/ www.js

#!/usr/bin/nodejs
var debug = require('debug')('my-application');
var app = require('../app');

app.set('port', process.env.PORT || 3000);

var io = require('socket.io').listen(app.listen(app.get('port')));

io.sockets.on('connection', function(socket) {
  console.log('Client connected!');
  socket.on('message', function(data) {
    console.log('Sending update!');
    socket.emit('update', 'Working!');
  });
});

公开/ Javascript角/ update.js

var socket = io.connect('http://' + document.location.hostname + ':3000/');

socket.on('connect', function() {
  console.log('Socket connected!');
  socket.emit('message', 'Message from client');
});

socket.on('update', function(data) {
  alert(data);
});

当我结束npm进程时,客户端开始记录

http://<ip>:3000/socket.io/?EIO=2&transport=polling&t=1498772846992-691 net::ERR_CONNECTION_REFUSED

我已经阅读了有关快速路由器搞乱套接字请求的帖子,但无论我尝试什么,我似乎都无法正常工作。

2 个答案:

答案 0 :(得分:1)

你可以尝试这个设置吗?

编辑:

app.js:

var express = require('express');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
app.get('/', function (req, res) {
    res.render('index');
});

module.exports = app;  

仓/ www.js:

var app = require('../app');
var http = require('http');
var server = http.createServer(app);
server.listen(process.env.PORT || '3000', function () {
    console.log('server listens on port 3000');
});
var io = require('socket.io')(http);
io.listen(server);

io.on('connection', function(socket) {
    console.log('Client connected!');
    socket.on('message', function (data) {
        console.log('Sending update!');
        socket.emit('update', 'Working!');
    });
});

index.pug(或玉,他们说玉已经过时):

doctype html
html
  body
    h1 Testing socket.io
    h3#status not connected 
    br  
    p#update update:&nbsp

    script(src="/socket.io/socket.io.js")
    script.
      var socket = io();
      socket.on('connect', function() {
        document.getElementById("status").innerHTML = "connected";   
        socket.emit('message', 'Hello!');
      });
      socket.on('update', function (data) {
          document.getElementById("update").innerHTML += data;  
      });

答案 1 :(得分:0)

调用\\(其中app.listen是调用app的结果)返回express(),可用于设置套接字连接:

HTTPServer

没有手动运行你的解决方案,我猜是因为你正在创建一个新的var server = app.listen(port); var io = socket(server); 来加入套接字,它会以某种方式挂起来。