brotoBuf.js在LayaAir上与Node.js后台交互

废话不多说直接上代码,也可到我的github上面下载源码

客户端代码如下,记得在index.html 里引入 socket.io.js

(function()
{
  var Loader = Laya.Loader;
  var Browser = Laya.Browser;
  var Handler = Laya.Handler;

  var ProtoBuf = Browser.window.protobuf;

  Laya.init(550, 400);

  ProtoBuf.load("../res/protobuf/awesome.proto", onAssetsLoaded);
  var buffer;
  var AwesomeMessage;

  function onAssetsLoaded(err, root)
  {
    if (err)
      throw err;

    // Obtain a message type
    AwesomeMessage = root.lookup("awesomepackage.AwesomeMessage");

    // Create a new message
    var message = AwesomeMessage.create(
      {
        awesomeField:'client',
        age:25,
        people:{age:13,name:'alpha_client'}
      }
    );

    // Verify the message if necessary (i.e. when possibly incomplete or invalid)
    var errMsg = AwesomeMessage.verify(message);
    if (errMsg){
      throw Error(errMsg);
    }

    // Encode a message to an Uint8Array (browser) or Buffer (node)
    buffer = AwesomeMessage.encode(message).finish();
    // ... do something with buffer
    // Or, encode a plain object
    // var buffer = AwesomeMessage.encode(
    // {
    // 	awesomeField: "AwesomeString"
    // }).finish();
    // ... do something with buffer
    console.log(buffer);
    // // Decode an Uint8Array (browser) or Buffer (node) to a message
    // buffer = formatBuffer(buffer)
    // console.log(buffer.toBuffer());
    // buffer = new Uint8Array(buffer)
    // console.log(buffer);
    
    // var message1 = AwesomeMessage.decode(buffer);
    // console.log(message1);
    // console.log(message1.people.age);
    // console.log(message1.people.name);
    // ... do something with message
    
    // If your application uses length-delimited buffers, there is also encodeDelimited and decodeDelimited.
  }

  var socket;
  socket = io.connect('http://game.alphayan.cn:8080');
  
  socket.on('error', function() {
    	console.log("与服务器连接发生错误");
  });
  socket.on('connecting', function() {
    	console.log("正在与服务器连接");
  });
  socket.on('connect', function() {
    	console.log("与服务器连接成功");
    socket.emit('login',buffer);
  });

  socket.on('connect_failed', function() {
    	console.log("与服务器连接失败");
  });

  socket.on('disconnect', function() {
    	console.log("与服务器断开");
  });

  socket.on('reconnect', function() {
    	console.log("重新连接到服务器");
  });
  socket.on('login', function(data) {
    var buffer1 = new Uint8Array(data)
    
    	console.log("login "+buffer1);

    var message1 = AwesomeMessage.decode(buffer1);
    console.log(message1);
    console.log(message1.people.age);
    console.log(message1.people.name);
  });

})();

proto协议文件:

package awesomepackage;
syntax = "proto3";



message AwesomeMessage {
    required string awesomeField = 1; // becomes awesomeField
    required int32 age = 2;
    message peopleMsg {
        string name = 1;
        int32 age = 2;
    }
    required peopleMsg people = 3;
}

后台用node.js开发

var ProtoBuf = require("protobufjs");
var ProtoRoot = ProtoBuf.loadSync("./proto/awesome.proto");
var AwesomeMessage = ProtoRoot.lookupType("awesomepackage.AwesomeMessage");
var mysql      = require('mysql');
///连接mysql
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : '****',
  password : '******',
  database : '********'
});
connection.connect();
/////---------------------
///*
var message = AwesomeMessage.create(
    {
      awesomeField:'server',
      age:10,
      people:{age:14,name:'alpha_svr'}
    }
);
var errMsg = AwesomeMessage.verify(message);
  if (errMsg){
  	throw Error(errMsg);
}
var buffer = AwesomeMessage.encode(message).finish();
console.log(buffer);
//var message1 = AwesomeMessage.decode(buffer);
//console.log(message1);
//*/

/////---------------------
function formatBuffer(buffer) {
    var bufferArray = Object.keys(buffer).map(function(k) {
        return buffer[k];
    })
    return new Buffer(bufferArray);
}

var io = require('socket.io')(8080);
var client;

io.on('connection', function (socket) {
  client = socket
  //断开
  socket.on("disconnect", OnClose);
      
  //登陆
  socket.on("login", OnLogin);
});

console.log('server is started, port: ' + '8080');		

var OnLogin = function(data){
  console.log('Onlogin1:' + data)
  data = formatBuffer(data)
  //console.log('Onlogin2:' + data)
  client.emit('login',buffer);
  var message = AwesomeMessage.decode(data);
  console.log(message.awesomeField +'\n' + message.age + '\n' + message.people.name + '\n' + message.people.age);
  /*
  var  addSql = 'INSERT INTO websites(Id,name,url,alexa,country) VALUES(1,?,?,?,?)';
  var  addSqlParams = ['alpha_node', 'https://c.runoob.com','23453', 'CN'];
  connection.query(addSql,addSqlParams,function (err, result) {
      if(err){
       console.log('[INSERT ERROR] - ',err.message);
       return;
      }
      console.log('--------------------------INSERT----------------------------');
      console.log('INSERT ID:',result);
      console.log('------------------------------------------------------------\n');
  });
  */
  var  sql = 'SELECT * FROM websites where Id=1';
  //查
  connection.query(sql,function (err, result) {
    if(err){
      console.log('[SELECT ERROR] - ',err.message);
      return;
    }
     console.log('--------------------------SELECT----------------------------');
     console.log(result);
     console.log('------------------------------------------------------------\n');  
  });
}

var OnClose = function(data){
  console.log('OnClose')

}

前台日志:

《brotoBuf.js在LayaAir上与Node.js后台交互》

后台日志:

-----从客户端手动的数据----
Onlogin1:[object Object]                                                                                                                                 
client                                                                                                                                                   
25                                                                                                                                                        
alpha_client                                                                                                                                              
13                                                                                                                                                        
------插入数据库---------
--------------------------INSERT----------------------------                                                                                              
INSERT ID: OkPacket {                                                                                                                                    
  fieldCount: 0,                                                                                                                                          
  affectedRows: 1,                                                                                                                                        
  insertId: 0,                                                                                                                                            
  serverStatus: 2,                                                                                                                                        
  warningCount: 0,                                                                                                                                        
  message: '',                                                                                                                                            
  protocol41: true,                                                                                                                                       
  changedRows: 0 }                                                                                                                                        
------------------------------------------------------------

 

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Are you human? Click the Banana...