服务器:
var
io=require('socket.io'),
express=require('express'),
UUID=require('node-uuid'),
path=require('path'),
app = express();
app.configure(function(){
app.use(express.static(path.join(__dirname,'')));
});
var server = require('http').createServer(app).listen(8080);
sio = io.listen(server);
app.get('/', function(req, res){
res.sendfile('/index.html', {root:__dirname});
});
sio.sockets.on('connection', function(socket){
socket.userid = UUID();
socket.on('message', function(){
console.log('client just sent something');
socket.emit('news', { hello: 'world' });
});
});
客户端首先连接index.html,然后点击href到gameroom.html。这是gameroom.html:
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="game.room.js"></script>
<script type="text/javascript" src="client.js"></script>
</head>
</html>
client.js:
window.onload = function(){
var game = new game_room();
}
game.room.js:
var game_room = function(){
this.socket = io.connect();
this.socket.on('connect', function(){
this.socket.emit('message', 'Hello server');
});
}
当客户端连接时,它应该发出消息并且服务器写入日志,但是我没有得到任何日志。我在game.room.js中尝试了没有this.socket.on('connect')的代码,客户端可以发出消息,我得到了日志。另外,如果我将代码从game.room.js传输到client.js,即在window.onload中我创建了var socket = io.connect()和socket.on('connect',function(){socket.emit( 'messsage','你好服务器')});它工作正常。
有人可以帮我解释或解释发生了什么吗?感谢。
答案 0 :(得分:0)
var game_room = function(){
this.socket = io.connect();
this.socket.on('connect', function(){
this.socket.emit('message', 'Hello server');
}.bind(this));
}
或者您可以将this.socket
设置为某些本地var:
var game_room = function(){
var socket = this.socket = io.connect();
this.socket.on('connect', function(){
socket.emit('message', 'Hello server');
});
}