客户端在连接到网站时没有点击io.on('connection')

时间:2015-07-05 05:51:39

标签: javascript node.js express socket.io

服务器运行正常,它正在点击MongodDB回调就好了,但它没有达到io.on('connection')回调。没有错误出现,所以我不确定是什么问题。

var express = require('express');
var consolidate = require('consolidate');

var app = express();
var server = require('http').createServer(app);

//Create the AlchemyAPI object
var AlchemyAPI = require('./alchemyapi');
var alchemyapi = new AlchemyAPI();

// all environments
app.use(express.static(__dirname + '/public'));
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
var MongoClient = require('mongodb').MongoClient; // MONGO DB
var Server = require('mongodb').MongoClient;
var http = require('http').Server(app);
var io = require('socket.io')(http);
// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}




var port = process.env.PORT || 3000;
server.listen(port, function(){
    console.log('Express server listening on port ' + port);
});

MongoClient.connect('mongodb://NotPasswordAndNotUsername@serverlocation:12345/db', function(err, doc){
    console.log("Got to callback");
    io.on('connection', function(socket){
console.log('Got here');
    });
});

这是我的客户端代码(index.html):

<!doctype html>
<html>
  <head>
    <title>Website title</title>
  <script type="text/javascript" src="https://code.jquery.com/jquery-1.8.0.min.js"></script>  
  <script src="https://apis.google.com/js/client.js?onload=onJSClientLoad"></script>
  <script src='http://' + location.hostname + ':3000/socket.io/socket.io.js'></script>
  <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
  </head>
  <body>
...
  </body>
</html> 

1 个答案:

答案 0 :(得分:1)

您正在聆听server对象而不是http。所以尝试将它传递给socket.io而不是:

var io = require('socket.io')(server);