在同一端口上运行socket.io 2.0和Express 4.0+

时间:2017-06-24 09:36:15

标签: node.js sockets express socket.io

我之前在Node项目上安装了socket.io,而不需要表达模板框架。

问题

如果我添加这行代码:http.listen(3001, function() { console.log('listening on port 3001'); });然后访问localhost:3000我的应用程序套接字不起作用 on localhost:3001我有套接字工作即可。我如何合并这两个?

错误

socket.io.js:2 GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=LpQ6zKP net::ERR_CONNECTION_REFUSED

我正在尝试在快速框架中添加socket.io,如下所示:

app.js文件

const express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var flash = require('connect-flash');
var multer = require('multer');
var upload = multer({ dest: './uploads' });
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;

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

var app = express();
var http = require( "http" ).createServer( app );
var io = require( "socket.io" )( http );
http.listen(3000, "127.0.0.1");

var httpk = require('http');
var nsp = io.of('/channel1');
var connectCounter = 0;
var interval = undefined;

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


app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect jQuery JS
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect Bootstrap CSS

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

//Handle express sessions
app.use(session({
    secret:'secret',
    saveUninitialized: true,
    resave:true
}));

// Passport
app.use(passport.initialize());
app.use(passport.session());

// Validator
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//For flash messages
app.use(flash());
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

app.get('*', function(req, res, next){
    res.locals.user = req.user || null;
    next();
});

app.use('/', index);

function test() {
    httpk.get("api-url", function(res) {
        var body = '';
        res.on('data', function(data) {
            body += data;
        });

        res.on('end', function() {
            var parsed = JSON.parse(body);
            //console.log(parsed.data.product1);
            var dataArray = [];
            dataArray.push((parseFloat(parsed.data.product1) + Math.random() * 0.1 + 0.01).toFixed(2));
            dataArray.push((parseFloat(parsed.data.product2) + Math.random() * 0.1 + 0.01).toFixed(2));
            console.log(dataArray);
            nsp.emit('live-quote', dataArray);
        });
    });
}


nsp.on('connection', function(socket) {

    socket.on('pass_data', function(my) {
        console.log(my);
    });

    //Make a http call
    connectCounter++;
    if (interval === undefined) interval = setInterval(test, 1000);
    nsp.emit('live-users', connectCounter);
    console.log('1 user connected, Total Joined: ' + connectCounter);

    socket.on('disconnect', function() {
        connectCounter--;
    if (connectCounter <= 0 && interval !== undefined) interval = clearInterval(interval);
        nsp.emit('live-users', connectCounter);
        console.log('1 user disconnected, Total Left: ' + connectCounter);
    });
    console.log("total clients: " + io.engine.clientsCount);
});


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

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

head.ejs

<title><%= title %></title>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>

<link rel='stylesheet' href='/stylesheets/style.css' />
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" >

jsdefaults.ejs

<script src="/javascripts/script.js" ></script>

<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>

  <script>
  $(function() {
    var socket = io('/channel1');
    var currentTime;

    socket.on('live', function(msg) {

        console.log("msg: "+msg);

    });

    socket.on('live-users', function(users) {
        $('#total').text(users);
    });
});

</script>

index.ejs

<!DOCTYPE html>
<html>
  <head><% include partials/head.ejs %></head>
  <body>
    <% include partials/header.ejs %>
    <div class="container" style="margin-top:20px;">

</div>
    <% include partials/footer.ejs %>
    <% include partials/jsdefaults.ejs %>
  </body>
</html>

1 个答案:

答案 0 :(得分:2)

看起来您使用express-generator来设置Express应用程序,在这种情况下,HTTP服务器将在bin/www中设置,socket.io服务器的位置也应该设置(因为你想在Express和socket.io之间共享HTTP服务器。)

默认bin/www包含:

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

您添加socket.io服务器的位置:

var server = http.createServer(app);
var io     = require('socket.io')(server);
var nsp    = io.of('/channel1');

nsp.on('connection', ...);