2017-06-24 57 views
0

我已經在Node項目上安裝了socket.io,而無需使用快速模板框架。在同一端口上運行socket.io 2.0和Express 4.0+

問題

,如果我加入這行代碼:http.listen(3001, function() { console.log('listening on port 3001'); });然後訪問本地主機:3000我有我的應用程序,其中插座不工作在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> 
+0

你做服務器的監聽器?像'server.listen(3000,()=> {// lol})'? –

+0

@FelixFong它正在監聽端口3000我猜。我不知道我找不到server.listen的代碼,但是當我輸入npm start時。我正在訪問本地主機:3000,所以它正在監聽端口3000 –

+0

@FelixFong,如果我添加以下代碼行:http.listen(3001,function(){});然後在訪問本地主機:3000我有我的應用程序在哪些套接字不工作,並在localhost:3001我有套接字工作。我如何合併這兩個? –

回答

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', ...); 
+0

它運作得很好。但現在我有功能測試和nsp.on('連接',...);代碼在www文件中。我也將連接到數據庫並與之交互。有沒有一種方法,我可以在www文件上只有2或3行代碼,並且仍然在app.js文件上休息?我不確定如何使用mongo –

+1

@MurlidharFichadia tbh,'express-generator'的默認結構是PITA,您可能需要考慮完全重構您的應用程序並完全取出'bin/www'。 – robertklep

+0

我明白你的意思。我的項目不是很大,我想我會擺脫快遞發電機。謝謝 –

相關問題