我只是想在按钮Click上发送一条从客户端到服务器的简单消息。
修改
当我的index.jade加载时,我使用以下代码并创建socket.io对象,然后将其转发给我的Menu_Contoller
,Menu_Model
又将套接字对象分配给SendOptionSelectedToServer
。然后每当函数{调用Menu_Model.js
的{1}}我使用Menu_Model
的套接字对象。此函数中的值是正确的。只是不知道为什么它不是emitting
。
index.jade
script(src = '/socket.io/socket.io.js')
script(src = '/javascripts/Menu_Controller.js')
script(src = '/javascripts/Menu_Model.js')
script
var socket = io.connect('http://localhost:3000');
socket.emit('GameType','chutia');
var Menu_Control = Object.create(Menu_Controller);
Menu_Control.Init(socket);
Menu_Controller.js
var Menu_Controller = {
Model : null,
Init:function(socket)
{
this.Model = Object.create(Menu_Model);
this.Model.Init(socket,this);
},
SendOptionSelectedToServer:function(option) <-- called from a view menu which we don't have to care about because value in 'option' are correct.
{
this.Model.SendOptionSelectedToServer(option);
}
};
Menu_Model.js
var Menu_Model = {
Socket : null,
Controller : null,
Init:function(sock,controllerRef)
{
this.Socket = sock;
this.Controller = controllerRef;
},
SendOptionSelectedToServer:function(option)
{
this.Socket.emit(option.type,option.ghostName); <-- this line.
}
};
这是我在 app.js 中的完整服务器端代码。
var express = require('express')
, http = require('http')
, routes = require('./routes')
, io = require('socket.io')
, factory = require('./serverfactory.js');
var app = express();
var server = app.listen(3000);
io = io.listen(server);
io.sockets.on('connection',function(socket){
console.log('new user'); <-- this is printed in the log.
socket.on('GameType',function(msg){
console.log(msg); <-- but this is not.
});
});
//var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
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());
});
// Routes
app.get('/', routes.index);
当发生新连接时,它会在日志中写入new user
。但是当从客户端使用emit
进行调用时,它不会在控制台中写入任何消息。我已经在客户端检查了params并且它们是正确的。客户端的option.type
将包含GameType
。
为什么不在客户端调用该事件?