我刚刚将socket.io添加到我的MEAN堆栈应用程序中。它的联系并不一致。这是我启动服务器并通过浏览器连接时得到的结果:
GET /socket.io/?EIO=3&transport=polling&t=LTnYzIi 200 1.948 ms - 3956
POST /socket.io/?EIO=3&transport=polling&t=LTnYzJL 404 1.617 ms - 66
GET /socket.io/?EIO=3&transport=polling&t=LTnYzrU 200 1.612 ms - 3956
POST /socket.io/?EIO=3&transport=polling&t=LTnYzs6 404 1.974 ms - 66
GET /socket.io/?EIO=3&transport=polling&t=LTnY-jT 200 1.652 ms - 3956
POST /socket.io/?EIO=3&transport=polling&t=LTnY-kE 404 0.975 ms - 66
但是,如果我在浏览器发出请求时(在后台)停止服务器并重新启动它,则客户端连接并且工作正常。它真的必须连接每次通信权利吗?请告诉我我错过了什么。
这是我的package.json socket.io电话:
"socket.io": "^1.4.6"
我的app.js看起来像这样:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator')
var mongodb = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/newphase1");
var async = require('async');
var config = require('./config.js');
var routes = require('./routes/index');
var api = require('./routes/api');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(favicon(__dirname + '/public/favicon(4).png'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/public')));
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
};
}
}));
var api = require('./routes/api')(app,express,io);
app.use('/api', api);
app.get('*',function(req,res){
res.sendFile(__dirname + '/public/views/index.html');
});
io.on('connection', function(socket) {
console.log('client connected!');
});
http.listen(config.port,"127.0.0.1",function(err){
if(err){
console.log(err);
}else{
console.log('listening on port 3000');
}
})
我的index.io脚本文件(来自CDN)在我的index.js(angular)中:
<script src="https://cdn.socket.io/socket.io-1.4.6.js"></script>
我对socket.io的服务:
.factory('socketio',function($rootScope){
var socket = io.connect("http://localhost:3000");
return {
on: function(eventName,callback){
socket.on(eventName,function(){
var args = arguments;
$rootScope.$apply(function(){
callback.apply(socket,args);
});
});
},
emit: function(eventName,data,callback){
socket.emit(eventName,data,function(){
var args = arguments;
$rootScope.apply(function(){
if(callback){
callback.apply(socket,args);
}
});
});
}
}
});
它确实已连接,但不一致。有任何想法吗?
答案 0 :(得分:0)
出于某种原因
npm start
给了我上面的不一致
node app.js
工作正常。