我在一个名为server.js的文件和index.html中有以下代码
由于某些原因,当我在web浏览器中导航到我的服务器时,io.on('connection')部分没有在其回调中调用console.log方法。
检查下面的代码,它说明了一切。 server.js
var express = require('express'),
app = express(),
io = require('socket.io')(app.Server),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
apiRouter = require('./app/routes/api.js');
//Clears Node Console.
process.stdout.write(' 33c');
console.log('Server starting!');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(apiRouter);
app.use(express.static('public'));
app.use('*', function(req, res, next) {
//All requests return single page angular application.
res.sendFile(__dirname + '/public/index.html');
});
mongoose.connect('localhost', 'triviaattack', function(err) {
if (err) {
console.log('An error occured when connecting to the MongoDB Database');
throw err;
}
});
io.on('connection', function(socket) {
console.log('client connected via socket'); //This is the line that isn't being called
});
app.listen(1337, function() {
console.log('Server started successfully @ ' + Date());
});
index . html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular-route.min.js"></script>
<script src="./app/app.js"></script>
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script>
var socket = io();
</script>
</head>
<body>
<div ng-controller="HomeCtrl">
{{message}}
</div>
</body>
</html>
找到答案了
必须将server.js更改为以下内容,注意顶部附近的新http变量。仍然有点好奇,为什么只是通过app.Server不工作在我原来的帖子…哦。
var app = require('express')(),
http = require('http').Server(app),
io = require('socket.io')(http),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
apiRouter = require('./app/routes/api.js');
//Clears Node Console.
process.stdout.write(' 33c');
console.log('Server starting!');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(apiRouter);
app.use('*', function(req, res, next) {
//All requests return single page angular application.
res.sendFile(__dirname + '/public/index.html');
});
mongoose.connect('localhost', 'triviaattack', function(err) {
if (err) {
console.log('An error occured when connecting to the MongoDB Database');
throw err;
}
});
io.on('connection', function(socket) {
console.log('client connected via socket');
});
http.listen(1337, function() {
console.log('Server started successfully @ ' + Date());
});