由于某种原因,我无法使用cloud9连接到socket.io。
节点app.js
var express = require('express')
, app = express()
, server = require('http').createServer(app)
, path = require('path')
, io = require('socket.io').listen(server);
app.configure(function(){
app.set('domain', process.env.IP);
app.set('port', process.env.PORT);
app.use(express.urlencoded());
app.use(express.json());
app.use(express.methodOverride());
app.use(express.compress());
app.use(express.responseTime());
// app.use(cors({credentials: false}));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://run.plnkr.co");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Credentials", true);
next();
});
app.use(express.static(path.join(__dirname, '/html')));
});
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});
// routes
app.use(app.router);
//sockets
io.sockets.on('connection', function(sock){
console.log('connected!', sock);
setInterval(function () {
sock.emit('send:time', {
time: (new Date()).toString()
});
}, 1000);
});
io.sockets.on('error', function(data) {
console.log('error', data, arguments);
});
// start app
app.listen(app.get('port'));
客户端app.js(有角度)
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['$scope', 'socket', function($scope, socket) {
socket.on('send:version', function (data) {
$log.log('send:version', data);
$scope.version = data.version;
});
socket.on('send:time', function (data) {
$log.log('send:time', data);
$scope.time = data.time;
});
}]);
app.factory('socket', [
'$rootScope'
, '$log'
, function (
$rootScope
, $log
) {
var socket = io.connect('https://demo-project-c9-chovy.c9.io');
$log.log('socket', io, socket);
socket.on('connect', function() {
$log.log('Connected!');
});
socket.on('error', function() {
$log.log('error!', arguments);
});
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);
}
});
})
}
};
}]);
我怀疑问题是cloud9使用代理而无法为socket.io/1资源提供服务。
以下是我从angular连接的方式:
var socket = io.connect('https://demo-project-c9-chovy.c9.io');
如果我这样做,我会得到404。
如果我使用端口8080,我最终会在客户端获得套接字错误事件。
答案 0 :(得分:0)
我在节点app.js文件中需要server.listen(port, cb)
而不是app.listen(port)
。