本文介绍了在同一端口上运行socket.io 2.0和Express 4.0+的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前已经在Node项目上安装了socket.io,而无需使用快速模板框架.

I have installed socket.io before on a Node project without the need of express templating framework.

如果我添加以下代码行: http.listen(3001,function(){console.log('listening on port 3001');}); 然后访问本地主机:3000我我的应用程序在 sockets不起作用,并且在localhost:3001上我的套接字在工作.我如何合并这两个?

if I add this line of code: http.listen(3001, function() { console.log('listening on port 3001'); }); then on visiting localhost:3000 I have my app in which sockets does not work and on localhost:3001 I have sockets working. How do I merge both of these?

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

我试图在如下所示的快速框架中添加socket.io:

I am trying to add socket.io in express framework like below:

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>

推荐答案

您似乎使用 express-generator 设置了Express应用程序,在这种情况下,将在以下位置设置HTTP服务器 bin/www ,这也是应该在其中设置 socket.io 服务器的原因(因为您希望在Express和 socket.io ).

It looks like you used express-generator to set up your Express application, in which case the HTTP server will be set up in bin/www and that's where the socket.io server should be set up as well (since you want to share the HTTP server between Express and socket.io).

默认的 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', ...);

这篇关于在同一端口上运行socket.io 2.0和Express 4.0+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:35