我几天前才开始使用 node.js,我知道尝试使用 socket.io 模块。但它没有像我预期的那样工作。我试图重现的例子是这个: http://robdodson.me/blog/2012/06/04/deploying-your-first-node-dot-js-and-socket-dot-io-app-to-heroku/
我知道他们使用的 Express 版本已经过时,所以我更新了我的代码以适应他们使用的模块的新版本。
我遇到的问题是我的客户端没有得到我的服务器发出的信息,这是我的服务器端代码:
var express = require('express'),
http = require('http'),
app = express(),
port = 8080, // Use 8079 for dev mode
server = http.createServer(app).listen(process.env.PORT || port, function(){
console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env);
}),
io = require('socket.io').listen(server),
routes = require('./routes');
// Configuration
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function() {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function() {
app.use(express.errorHandler());
});
// Heroku won't actually allow us to use WebSockets
// so we have to setup polling instead.
// https://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
// Routes
app.get('/', routes.index);
var status = "All is well.";
io.sockets.on('connection', function (socket) {
io.sockets.emit('status', { status: status }); // note the use of io.sockets to emit but socket.on to listen
socket.on('reset', function (data) {
status = "War is imminent!";
io.sockets.emit('status', { status: status });
});
});
这是客户端:
<script src="http://localhost:8080/socket.io/socket.io.js">
var socket = io.connect(document.location.href);
</script>
<div id="status"></div>
<button id="reset">Reset!</button>
因此,如果我理解得很好,我应该在状态 div 中第一次得到“All is well”,以及“War is imminent !”如果我点击重置。 但我一无所获。
我尝试了这些答案,但我看不出解决方案代码与我的代码有任何区别,或者有时它只是过时了: 1. Node.js + socket.io: app on server not working correctly 2. NodeJS - Socket.IO Setup: served static content no handshake (Ubuntu on Rackspace Cloud Server)
我尝试了其他主题中提供的所有解决方案,但它肯定不适合我。 每个模块都已正确安装。我按照我最初遵循的教程中给出的步骤进行操作。 如果有人对正在发生的事情有任何想法,或者如果有人遇到过同样的问题,欢迎您。
谢谢。
最佳答案
您的客户没有做任何事情的原因是您没有告诉它做任何事情。您需要为其分配处理程序才能执行某些操作。因此,要解决此问题,您需要告诉 reset
按钮在被单击时使用 socket.emit()
,并且您还需要分配一个处理程序为 status
事件更改 div
的内容。
<script type="text/javascript" src="http://localhost:8080/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect(document.location.href);
</script>
<div id="status"></div>
<button id="reset" onclick="socket.emit('reset')">Reset!</button>
<script type="text/javascript">
socket.on('status', function(data) {
document.getElementById('status').innerHTML = data.status;
});
</script>
关于javascript - Node.JS - 简单的 Socket.IO 示例不起作用。获取调试 - 提供静态内容/socket.io.js (Mac OSX/Localhost),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19613936/