【发布时间】:2016-03-01 19:17:12
【问题描述】:
我无法让 socket.io 与我的使用 Grunt 的项目一起工作。我目前正在通过凉亭使用 angular-socket-io。以下是我到目前为止所做的事情:
1) 通过 bower 安装 angular-socket-io 和 socket.io-client
2) 将以下行完全导入index.html
<script src="bower_components/socket.io-client/socket.io.js"></script>
<script src="bower_components/angular-socket-io/socket.min.js"></script>
3) 在我的 app.js 中添加了“btford.socket-io”
angular.module('angularApp', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute', 'ui.bootstrap', 'btford.socket-io'])
4) 制作Socket.js 文件
app.factory('Socket', ['socketFactory', '$location',
function(socketFactory, $location) {
if($location.host() === "127.0.0.1") {
return socketFactory({
prefix: '',
ioSocket: io.connect($location.protocol() + '://' + $location.host() + ':' + $location.port())
});
} else {
return socketFactory({
prefix: '',
ioSocket: io.connect({path: '/node_modules/socket.io'})
});
}
}
]);
项目结构:
Project
|
- node_modules
|
- socket.io
- src
|
- main
|
- webapp
|
- app
|
- bower_components
- scripts
|
- controllers
- services
- app.js
- Socket.js
- styles
- views
- index.html
- bower.json
- Gruntfile.js
- server.js
但每次投票时我都会收到以下错误:
GET http://127.0.0.1:9000/socket.io/?EIO=3&transport=polling&t=1448635105443-105 404 (Not Found)
可能出了什么问题?是否可以告诉 Angular 导入节点的某些特定模块?我一直在从 stackoverflow 中搜索解决方案,并且在 Google 上搜索了很多天,但我没有找到任何解决方案。
但是我发现,当它尝试使用该地址获取 socket.io 时,它会尝试从 node_modules 路径中获取它。我已经在那里安装了,以防socket.io通过npm。
我还阅读了 Github angular-socket-io angular-socket-io 的说明
编辑*
我试图创建server.js,其中包括以下几行:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(9000, "127.0.0.1");
function handler (req, res) {
fs.readFile(__dirname + '/src/main/webapp/app/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function(socket){
socket.emit('news', {message: 'hello world'});
socket.on('my event', function(data){
console.log(data);
})
})
但它仍然说同样的话。
【问题讨论】:
-
尝试使用 io.on 而不是 io.sockets.on
-
@Gary:试过但没有帮助。
-
客户端尝试联系服务器这一事实很好,因为这意味着您很可能正确设置了客户端。您的问题似乎在服务器端。你能加载 index.html 吗?确保您的服务器确实在运行。
-
@Gary:我正在使用
grunt serve来运行我的前端。我在Gruntfile.js中配置了server.js文件将被监视。我也做了简单的测试,我在server.js中写了这行console.log("Testing");然后运行grunt serve命令,它打印得很好,但当然不是在浏览器控制台中,而是在命令提示符中,因为我在 Windows 中运行我的项目带有本地主机的环境。关于加载 index.html,至少我没有收到“加载 index.html 时出错”消息,所以我假设我没有从那一侧得到错误。
标签: javascript angularjs node.js socket.io