Skip to content
Browse files

misc:add comment and readme

  • Loading branch information...
1 parent e08ed60 commit a787c428d57b8407764d95c1b71288667f5a33d4 @piaohai piaohai committed Aug 22, 2012
View
22 LICENSE
@@ -0,0 +1,22 @@
+(The MIT License)
+
+Copyright (c) 2012 Netease, Inc. and other pomelo contributors
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+'Software'), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
View
69 README.md
@@ -0,0 +1,69 @@
+#pomelo-robot
+pomelo-robot is simple tool to benchmark the socket.io server performance.
+
+pomelo-robot can run in multiple mode such as single machine with many process
+,distribute test many socket.io server.
+
+pomelo-robot execute developer custom JavaScript in a sand box and static
+monitor include max(min,avg) response time and QPS,etc. then report to web http
+server with graph display
+
+pomelo-robot also can be used in http benchmark by developer script;
+
+
+##Installation
+```
+npm install pomelo-robot
+```
+
+##Usage
+``` javascript
+
+var Robot = require('pomelo-robot').Robot;
+//developer custom data source with data application
+var queryHero = require('./app/data/mysql').queryHero;
+//config the master and app,detail by demo
+var config = require('./app/config/config');
+var fs = require('fs');
+
+var robot = new Robot(config);
+
+if (robot.server==='master') {
+ robot.run(__filename);
+} else {
+ var mysql =config[robot.env].mysql;
+ var Client = require('mysql').Client;
+ var client = new Client();
+ client.host = mysql.host;
+ client.user = mysql.user;
+ client.password = mysql.password;
+ client.database = mysql.database;
+ var args = process.argv;
+ var i = 5;
+ var limit = args[i++];
+ var offset= args[i++];
+ //developer execute script
+ var script = fs.readFileSync(process.cwd() + '/app/config/lord.js', 'utf8');
+ queryHero(client,limit,offset,function(error,users){robot.run(users,script)});
+}
+
+```
+
+##API
+###robot.runMaster()
+run master server and http server,then initial server status include
+clients,start up file.
+####Arguments
++ startUpFile - The master server auto start up agent file name, default is
+ current run file;
+
+###robot.runAgent()
+robot run in client agent mode.
+####Arguments
++ datasource - The Array data ,and the size is the concurrent users.
++ script - The developer custom script that agent should be execute.
+
+###Notice
+when pomelo-robot run in distribute mode, every client should be in same
+directory path and master could be ssh login automatic. Otherwise developer can
+start up agent by self,for the custom script, the demo is attachment.
View
12 lib/agent/agent.js
@@ -4,11 +4,18 @@ var logging = require('../common/logging').Logger;
var Machine = require('./machine').Machine;
var monitor = require('../monitor/monitor');
-var STATUS_INTERVAL = 60 * 1000; // 60 seconds
+var STATUS_INTERVAL = 10 * 1000; // 60 seconds
var RECONNECT_INTERVAL = 15 * 1000; // 15 seconds
var HEARTBEAT_PERIOD = 30 * 1000; // 30 seconds
var HEARTBEAT_FAILS = 5; // Reconnect after 3 missed heartbeats
+/**
+ *
+ * @param {Object} conf
+ * init the master and app server for the agent
+ * include app data, exec script,etc.
+ *
+ */
var Agent = function(conf) {
this.log = logging;
this.conf = {};
@@ -26,7 +33,6 @@ var Agent = function(conf) {
};
Agent.prototype = {
-
// Create socket, bind callbacks, connect to server
connect: function() {
var agent = this;
@@ -90,7 +96,7 @@ Agent.prototype = {
setInterval(function(){
var d = monitor.getData();
agent.socket.emit('report',{id:agent.nodeId,data:d});
- },5000);
+ },STATUS_INTERVAL);
},
close:function(){
View
8 lib/agent/machine.js
@@ -5,7 +5,13 @@ var fs = require('fs');
var io = require('socket.io-client');
var Robot = require('./robot').Robot;
-
+/**
+ *
+ *create machin instance
+ * @param {Object} app location,
+ * @param {Array} test case data
+ * @param {String} script
+ */
var Machine = function(app,user,script) {
EventEmitter.call(this);
this.conf = {};
View
48 lib/agent/robot.js
@@ -54,17 +54,21 @@ var pro = Robot.prototype;
/**
- *对延时操作的封装
+ * emit done event
+ *
*/
pro.done = function(){
//process.exit();
this.emit('done',this.user.uid);
};
/**
- * 对发送数据的emit封装
+ * wrap socket.io emit message
+ *
+ *@param {Object} msg
+ *
*/
-pro.pushMessage = function(msg,watched){
+pro.pushMessage = function(msg){
//console.error('pushMessage message ' + JSON.stringify(msg));
var self = this;
if(!!msg)
@@ -74,7 +78,12 @@ pro.pushMessage = function(msg,watched){
var cbs = {};
/**
- * 对发送数据的send封装
+ *wrap socket.io send message
+ *
+ * @param {String} msg
+ * @param {Function} cb
+ * @param {Boolean} encdoe
+ *
*/
pro.request = function(msg,cb,encode){
var self = this;
@@ -90,7 +99,10 @@ pro.request = function(msg,cb,encode){
};
/**
- *对延时操作的封装
+ * wrap setTimeout
+ *
+ *@param {Function} fn
+ *@param {Number} time
*/
pro.later = function(fn,time){
if (time>0 && typeof(fn)=='function') {
@@ -99,10 +111,12 @@ pro.later = function(fn,time){
};
/**
+ * wrap setInterval
+ * when time is Array, the interval time is thd random number
+ * between then
*
- * 对interval操作的封装,
- * time为数组时,interval的时间为数组期间的随机数
- *
+ *@param {Function} fn
+ *@param {Number} time
*/
pro.interval = function(fn,time){
var fn = arguments[0];
@@ -123,13 +137,25 @@ pro.interval = function(fn,time){
}
};
-
-pro.clean = function(timeId){
- clearTimeOut(timeId);
+/**
+ *wrap clearTimeout
+ *
+ * @param {Number} timerId
+ *
+ */
+pro.clean = function(timerId){
+ clearTimeOut(timerId);
}
var id=1;
+/**
+ *encode message
+ *
+ * @param {Number} id
+ * @param {Object} msg
+ *
+ */
pro.encode = function(id,msg) {
return Protocol.encode(id,msg.route,msg);
}
View
9 lib/common/logging.js
@@ -8,8 +8,8 @@
*/
var Logger = function(log_level) {
- this._log_level = log_level ? log_level : 2
-}
+ this._log_level = log_level ? log_level : 2;
+};
Logger.prototype = {
_timestamp: function(msg) {
@@ -22,8 +22,7 @@ Logger.prototype = {
},
isDebug: function(msg) {
- if (this._log_level < 3) { return;false } else {return true;}
-
+ if (this._log_level < 3) { return false; } else {return true;}
},
info: function(msg) {
@@ -48,4 +47,4 @@ getLogger = function() {
return instance();
};
-exports.Logger = instance;
+exports.Logger = instance;
View
8 lib/common/util.js
@@ -15,11 +15,11 @@ var EventEmitter = require('events').EventEmitter;
// A few common global functions so we can access them with as few keystrokes as possible
//
var qputs = util.qputs = function(s) {
- { util.puts(s); }
+ util.puts(s);
};
var qprint = util.qprint = function(s) {
- { util.print(s); }
+ util.print(s);
};
@@ -45,13 +45,15 @@ util.extend = function(obj, extension) {
}
return obj;
};
+
util.forEach = function(obj, f) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
f(i, obj[i]);
}
}
};
+
util.every = function(obj, f) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
@@ -153,4 +155,4 @@ util.LineReader = function(eventEmitter, event) {
}
util.inherits(util.LineReader, EventEmitter);
-util.extend(exports, util);
+util.extend(exports, util);
View
2 lib/console/http.js
@@ -1,5 +1,5 @@
// ------------------------------------
-// HTTP Server hello git
+// HTTP Server
// ------------------------------------
//
// This file defines HttpServer and the singleton HTTP_SERVER.
View
10 lib/console/index.html
@@ -1,6 +1,6 @@
<html>
<head>
-<title>Pomelo Console</title>
+<title>Pomelo Robot Console</title>
<link rel="stylesheet" type="text/css" href="css/web_client.css" />
<link rel="stylesheet" type="text/css" href="css/colors.css" />
<script src="/js/lib/jquery.min.js"></script>
@@ -106,14 +106,12 @@
</div>
<div id='summary_div' style='display:none'></div>
-
- <!-- #stream_template -->
<div class="screen history" id="avg_div2" style="height:246px">
<div class="bar">
<span class="screen-label">响应时间表</span>
<div class="bar-top-right">
<div class="screen-buttons"><input type="button" class="add-button"
- id='avgbtn'" value='查看Agent'>&nbsp;<img id='avg_img' style='display:none'
+ id='avgbtn' value='查看Agent'>&nbsp;<img id='avg_img' style='display:none'
src="/images/icons/cross.png" title="Close Screen" />
</div>
<div class="screen-search">
@@ -127,7 +125,6 @@
</div>
<div id='avg_div' style='display:none'></div>
-
<div class="screen history" id="qs_div2" style="height:246px">
<div class="bar">
<span class="screen-label">吞吐率图表</span>
@@ -147,9 +144,6 @@
</div>
<div id='qs_div' style='display:none'></div>
-
- <!-- #history_template -->
-
<div id="bottom">
<div id="bottom2">
<div id="stats">
View
127 lib/main.js
@@ -2,59 +2,84 @@ var Agent = require('./agent/agent').Agent;
var Server = require('./master/server').Server;
var HTTP_SERVER = require('./console/http').HTTP_SERVER;
+/**
+ * export to developer prototype
+ *
+ * @param {Object} config
+ * include deal with master and agent mode
+ *
+ * param include env, agentId, mode
+ *
+ */
var Robot = function(config){
- this.args = process.argv;
- this.env = 'dev';
- this.agentId = 'agent1';
- this.server = 'master';
- this.config = config;
- this.master =null;
- this.apps = null;
- this.clients = null;
- this.pageSize = 10;
- this.init();
-}
+ this.args = process.argv;
+ this.env = 'dev';
+ this.agentId = 'agent1';
+ this.server = 'master';
+ this.config = config;
+ this.master =null;
+ this.apps = null;
+ this.clients = null;
+ this.pageSize = 10;
+ this.init();
+};
+/**
+ * parse the args
+ *
+ *
+ */
Robot.prototype.init = function(){
- var args = this.args;
- var config = this.config;
- var i = 2;
- if (args.length > 2){
- this.env = args[i++];
- this.server=args[i++];
- this.agentId = args[i++];
- }
- var env = this.env;
- this.master = config[env].master;
- this.apps = config[env].apps;
- this.clients = config[env].clients;
- if (this.server!=='master') {
- this.pageSize = args[7];
- }
-}
+ var args = this.args;
+ var config = this.config;
+ var i = 2;
+ if (args.length > 2){
+ this.env = args[i++];
+ this.server=args[i++];
+ this.agentId = args[i++];
+ }
+ var env = this.env;
+ this.master = config[env].master;
+ this.apps = config[env].apps;
+ this.clients = config[env].clients;
+ if (this.server!=='master') {
+ this.pageSize = args[7];
+ }
+ };
-Robot.prototype.run = function(data,script) {
- var conf = {},agent = null,server;
- if (this.server === 'master') {
- conf.env = this.env;
- conf.clients = this.clients;
- conf.main = data;
- server = new Server(conf);
- server.listen(this.master.port);
- HTTP_SERVER.start(this.master.webport);
- } else {
- conf.data = data;
- conf.master = this.master;
- conf.pageSize = this.pageSize;
- conf.apps = this.apps;
- conf.nodeId = this.agentId;
- conf.script = script;
- agent = new Agent(conf);
- agent.start();
- }
-}
+ /*
+ * run master server
+ *
+ * @param {String} start up file
+ *
+ */
+ Robot.prototype.runMaster = function(startUpFile) {
+ var conf = {},agent = null,server;
+ if (this.server !== 'master') {throw new Error(' server must be master,it is %j',this.server);}
+ conf.env = this.env;
+ conf.clients = this.clients;
+ conf.main = startUpFile;
+ server = new Server(conf);
+ server.listen(this.master.port);
+ HTTP_SERVER.start(this.master.webport);
+ };
-exports.Robot = Robot;
-//process.on('uncaughtException', function(err) {
-// console.error(' Caught exception: ' + err.stack);
-//});
+ /**
+ * run agent client
+ *
+ * @param {Array} data
+ * @param {String} script
+ *
+ */
+ Robot.prototype.runAgent = function(data,script) {
+ conf.data = data;
+ conf.master = this.master;
+ conf.pageSize = this.pageSize;
+ conf.apps = this.apps;
+ conf.nodeId = this.agentId;
+ conf.script = script;
+ agent = new Agent(conf);
+ agent.start();
+ };
+
+ exports.Robot = Robot;
View
3 lib/master/nodeclient.js
@@ -1,7 +1,6 @@
var __ = require('underscore');
-// NodeClient is a server/machine/instance running a harvester
-// It has nothing to do with node.js
+// NodeClient is a server/machine/instance running a agent socket
var NodeClient = function(nodeId, socket, server) {
this.nodeId = nodeId;
this.socket = socket;
View
36 lib/master/server.js
@@ -9,6 +9,15 @@ var starter = require('./starter');
var STATUS_INTERVAL = 60 * 1000; // 60 seconds
var HEARTBEAT_INTERVAL = 30 * 1000; // 30 seconds
+/**
+ *
+ * robot master instance
+ *
+ * @param {Object} conf
+ *
+ * conf.env runtime enviroment
+ * conf.main client run file
+ */
var Server = function(conf) {
this.log = logging;
this.nodes = {};
@@ -21,7 +30,6 @@ var Server = function(conf) {
this.clients = conf.clients;
var rserver = this;
- // Print status every minute
setInterval(function() {
rserver.log.info("Nodes: " + __(rserver.nodes).size() + ", " +
"WebClients: " + __(rserver.web_clients).size());
@@ -50,9 +58,7 @@ Server.prototype = {
var node = new _nodeclient.NodeClient(nodeId,socket, this);
rserver.nodes[nodeId] = node;
- //console.log(JSON.stringify(rserver.web_clients));
// Tell all WebClients about new Node
- //console.log('send message to client');
__(rserver.web_clients).each(function(web_client) {
web_client.add_node(node);
});
@@ -66,9 +72,8 @@ Server.prototype = {
});
socket.on('report', function(message) {
- //console.log('merge ' + nodeId + ' ' +message.id);
- rserver.io.sockets.in('web_clients').emit('statusreport',{id:nodeId,time:message.id,conf:rserver.runconfig});
- stat.merge(nodeId,message.id,message.data);
+ rserver.io.sockets.in('web_clients').emit('statusreport',{id:nodeId,time:message.id,conf:rserver.runconfig});
+ stat.merge(nodeId,message.id,message.data);
});
},
// Registers new WebClient with Server
@@ -82,8 +87,7 @@ Server.prototype = {
});
socket.on('webreport', function(message) {
- //console.log('webreport' + JSON.stringify(stat.getData()));
- socket.emit('webreport',stat.getData());
+ socket.emit('webreport',stat.getData());
});
socket.on('disconnect', function() {
@@ -95,7 +99,7 @@ Server.prototype = {
// Register announcement, disconnect callbacks
register: function() {
var rserver = this;
- rserver.io.set('log level', 1); // TODO(msmathers): Make configurable
+ rserver.io.set('log level', 1);
rserver.io.sockets.on('connection', function(socket) {
socket.on('announce_node', function(message) {
rserver.log.info("Registering new node " + JSON.stringify(message));
@@ -121,21 +125,11 @@ Server.prototype = {
});
});
- // Broadcast stats to all clients
- setInterval(function() {
- rserver.io.sockets.in('web_clients').emit('stats', {
- message_count: rserver.message_count
- });
- }, 1000);
-
// Broadcast heartbeat to all clients
setInterval(function() {
rserver.io.sockets.emit('heartbeat');
}, HEARTBEAT_INTERVAL);
- },
- getNode:function(msg){
- msg.socket.emit(msg.method,app.servers);
- },
-}
+ }
+};
exports.Server = Server;
View
60 lib/master/starter.js
@@ -5,16 +5,19 @@ var vm = require('vm');
var path = require('path');
var util = require('util');
-var starter = module.exports= new Starter();
+function Starter(){}
-function Starter() {
-}
+var starter = module.exports = new Starter();
var log = function () {
util.puts([].join.call(arguments, ' '));
};
-
+/**
+ *begin notify to run agent
+ *
+ *
+ */
Starter.prototype.run = function(env,message,clients){
if (!clients) {
clients = ['127.0.0.1'];
@@ -26,8 +29,8 @@ Starter.prototype.run = function(env,message,clients){
Starter.prototype.prepare = function(env,message,clients){
var self = this;
- var count = parseInt(message.agent) || 1;
- var limit = parseInt(message.maxuser) || 10;
+ var count = parseInt(message.agent,10) || 1;
+ var limit = parseInt(message.maxuser,10) || 10;
var ids = 0;
var index = 1;
for(var ipindex in clients) {
@@ -136,10 +139,6 @@ function spawnProcess(command, options, callback) {
});
}
-Starter.prototype.ensure = function (key, def) {
- if (starter.hasOwnProperty(key)) return;
- starter.set(key, def);
-};
Starter.prototype.set = function (key, def) {
if (typeof def === 'function') {
@@ -165,45 +164,6 @@ Starter.prototype.abort = function (msg) {
};
-Starter.prototype.sequence = function () {
- var args = arguments;
- starter.asyncLoop([].slice.call(args), function (arg, next) {
- if (typeof arg === 'function') {
- arg.call(starter, next);
- } else {
- starter[arg].call(starter, next);
- }
- });
-};
-
-Starter.prototype.asyncLoop = function asyncLoop(collection, iteration, complete) {
- var self = this;
- var item = collection.shift();
- if (item) {
- iteration.call(self, item, function next() {
- asyncLoop.call(self, collection, iteration, complete);
- });
- } else if (typeof complete === 'function') {
- complete.call(self);
- }
-};
-
-
-Starter.prototype.desc = function (text) {
-};
-
-Starter.prototype.task = function (name, action) {
- starter[name] = function task(done) {
- var displayName = name;
- log('Executing', displayName);
- var time = Date.now();
- action(function () {
- if (done) done();
- });
- };
- action.task = name;
-};
-
// Stylize a string
function stylize(str, style) {
var styles = {
@@ -224,7 +184,6 @@ function stylize(str, style) {
function $(str) {
str = new(String)(str);
-
['bold', 'grey', 'yellow', 'red', 'green', 'cyan', 'blue', 'italic', 'underline'].forEach(function (style) {
Object.defineProperty(str, style, {
get: function () {
@@ -234,4 +193,5 @@ function $(str) {
});
return str;
};
+
stylize.$ = $;
View
10 lib/master/webclient.js
@@ -10,7 +10,7 @@ var WebClient = function(socket, server) {
// Join web_clients room
socket.join('web_clients');
- // Remove WebClient from LogFiles
+ // Remove WebClient
socket.on('disconnect', function() {
__(wc.watching_logs).each(function(log_file) {
log_file.remove_web_client(wc);
@@ -21,22 +21,22 @@ var WebClient = function(socket, server) {
WebClient.prototype = {
- // Tell WebClient to add new Node, LogFiles
+ // Tell WebClient to add new Node
add_node: function(node) {
this.socket.emit('add_node', {
nodeId: node.nodeId,
iport:node.iport
});
},
- // Tell WebClient to remove Node, LogFiles
+ // Tell WebClient to remove Node
remove_node: function(node) {
this.socket.emit('remove_node', {
node: node.nodeId
});
}
-}
+};
module.exports = {
WebClient: WebClient
-}
+};
View
29 lib/monitor/monitor.js
@@ -1,3 +1,12 @@
+/**
+ *
+ * agent monitor data map
+ *
+ * every agent put start and end time in to route map
+ * then report to master
+ *
+ */
+
var monitor = module.exports;
var dataMap = {};
@@ -13,12 +22,12 @@ monitor.clear = function(){
};
monitor.beginTime = function(route,uid,time){
- if(!dataMap[route])
+ if(!dataMap[route]) {
dataMap[route] = buildRouteData();
-
- if(!dataMap[route][uid])
+ }
+ if(!dataMap[route][uid]){
dataMap[route][uid] = buildUserData();
-
+ }
var udata = dataMap[route][uid];
udata.start.push(time);
@@ -27,19 +36,17 @@ monitor.beginTime = function(route,uid,time){
monitor.endTime = function(route,uid,time){
- if(!dataMap[route])
+ if(!dataMap[route]){
dataMap[route] = buildRouteData();
-
- if(!dataMap[route][uid])
+ }
+ if(!dataMap[route][uid]){
dataMap[route][uid] = buildUserData();
+ }
var udata = dataMap[route][uid];
udata.end.push(time);
-
};
-
-
function buildRouteData(){
var data = {};
return data;
@@ -50,4 +57,4 @@ function buildUserData(){
data.start = [];
data.end = [];
return data;
-}
+}
View
26 lib/monitor/stat.js
@@ -1,7 +1,12 @@
+/**
+ * stat receive agent client monitor data
+ * merger vaild data that has response
+ * when server restart, it will clear
+ *
+ *
+ */
var __ = require('underscore');
-
var stat = module.exports;
-
var _dataMap = {};
stat.getData = function(){
@@ -21,7 +26,6 @@ stat.clear = function(agent){
if (!!agent) {
delete _dataMap[agent];
} else {
- delete _dataMap;
_dataMap = {};
}
};
@@ -30,13 +34,12 @@ stat.clear = function(agent){
function filter(params,index){
var data = {};
__.each(params,function(val,key){
- var times = [];
- //console.log(key + ' ' + __.size(val.start) + ' end ' + __.size(val.end) + ' val ' + JSON.stringify(val));
- __.each(val,function(dval,dkey){
- var ustart = dval['start'];
- var uend = dval['end'];
- //console.log(dkey + ' ' + __.size(ustart) + ' end ' + __.size(uend) + ' val ' + JSON.stringify(dval));
- if (__.size(ustart)==__.size(uend)){
+ var times = [];
+ __.each(val,function(dval,dkey){
+ var ustart = dval.start;
+ var uend = dval.end;
+ //console.log(dkey + ' ' + __.size(ustart) + ' end ' + __.size(uend) + ' val ' + JSON.stringify(dval));
+ if (__.size(ustart)==__.size(uend)){
for (var i = 0;i<__.size(ustart);i++){
var begin = ustart[i];
var end = uend[i];
@@ -47,8 +50,7 @@ function filter(params,index){
};
});
data[key] = times;
- //console.log('ssssssssssssssssssssssssss' + index + ' ' + __.size(times));
});
//console.log(' val ' + JSON.stringify(data));
return data;
-}
+};
View
4 package.json
@@ -1,9 +1,9 @@
{
"name": "pomelo-robot",
- "version": "0.0.15",
+ "version": "0.0.16",
"private": false,
"dependencies": {
- "socket.io-client": ">=0.9.6"
+ "socket.io-client": ">=0.9.6"
, "socket.io": ">=0.9.6"
, "underscore": ">=1.0.0"
, "pomelo-protocol": ">=0.0.2"
View
150 test/clientManager.js
@@ -1,150 +0,0 @@
-/**
- * 客户端与服务端的统一逻辑模块,负责调用客户端其他接口,完成逻辑实现
- * 以及与socketClient的交互工作
- * 负责客户端的初始化工作
- */
-
-__resources__["/clientManager.js"] = {meta: {mimetype: "application/javascript"}, data: function(exports, require, module, __filename, __dirname) {
-
-//var clientManager = require('Manager');
-var heroSelectView = require('heroSelectView');//选角色管理
-
-var socketClient = require('client');
-
-var loginUsername = "";
-var loginName = "";
-var sid = 0;
-var uid = 0;
-
-
-//暴露的接口和对象
-exports.init = init;
-exports.login = login;
-exports.register = register;
-exports.pickTreasure = pickTreasure;
-exports.move = move;
-exports.getCurrentScene = getCurrentScene;
-
-var self = this;
-
-self.uid = exports.uid = uid;
-
-
-
-function init(){
- //初始化socketClient
- socketClient.init();
-}
-
-/**
- * 登录逻辑,对应的推送消息格式:
- * msg = {
- * type: 1001 //消息类型
- * body: {
- * sid: , //用户的session id,登录时获得
- * treasureId: //宝物Id
- * }
- * }
- */
-function login(){
- var username = document.getElementById('loginUser').value;
- var pwd = document.getElementById('loginPwd').value;
-
- if (!username) {
- alert("请输入用户名");
- return;
- }
- // 登陆处理
- loginUsername = username;
- if(localStorage){
- localStorage.setItem('username', username);
- }
- socketClient.pushMessage({route:"connector.loginHandler.login", params:{username: username, password: pwd}});
-}
-
-/**
- * 注册逻辑,对应的消息格式:
- * msg = {
- * type: 1002,
- * body: {
- * username: //用户名
- * password: //密码
- * roleType: //角色类型
- * }
- * }
- */
-function register(){
- var roleId = heroSelectView.roleId();
- var name = document.getElementById('gameUserName').value;
- var pwd = "pwd";
-
- if (!loginUsername || !name) {
- alert("角色名不能为空");
- }
- else if(name.length > 9){
- alert('干嘛蛋疼取这么长的名字。。。');
- }
- else {
- socketClient.pushMessage({route:"connector.loginHandler.register", params:{username: loginUsername, name: name, password: pwd, roleId: roleId}});
- }
-}
-
-/**
- * 注册用户并获取当前场景信息
- */
-function getCurrentScene(){
- addUser();
- getOnlineUsers();
- getTreasures();
-}
-
-/**
- * 获取所有宝物信息
- */
-function getTreasures(){
- socketClient.pushMessage({route:"area.treasureHandler.getTreasures", params:{uid: uid}});
-}
-
-/**
- * 获取所有人物信息
- */
-function addUser(){
- socketClient.pushMessage({route:"area.userHandler.addUser"});
-}
-
-function getOnlineUsers(){
- socketClient.pushMessage({route:"area.userHandler.getOnlineUsers", params:{uid: uid}});
-}
-
-/**
- * 用户移动的处理逻辑
- * msg{
- * type: 3501,
- * body: {
- * sid: //用户的session id,登录时获得
- * path:[{x:,y:}] //移动的坐标列表,坐标格式为{x: x轴坐标, y: y轴坐标 },第一个坐标为起点,最后一点为终点
- * speed:
- * }
- * }
- */
-function move(startX, startY, endX, endY, time){
- path = [{x:startX, y:startY},{x:endX, y:endY}];
- socketClient.pushMessage({route:"area.userHandler.move", params:{path: path, time: time,uid: self.uid }});
-}
-
-/**
- * 当前用户捡起宝物
- * msg{
- * type: 3502
- * body: {
- * sid: //用户的session id,登录时获得
- * treasureId: //宝物Id
- * }
- * }
- */
-function pickTreasure(treasureId){
- socketClient.pushMessage({route:"area.treasureHandler.pickItem", params:{treasureId: treasureId}});
-}
-
-
-}};

0 comments on commit a787c42

Please sign in to comment.
Something went wrong with that request. Please try again.