自定义二进制协议的连接
var units = [
unit("起始符", "STRING", 2, [0x23, 0x23]),
unit("命令单元", "BYTE", 1),
unit("回复单元", "BYTE", 1),
unit("车辆识别码", "STRING", 17),
unit("数据加密方式", "BYTE", 1),
unit("数据单元长度", "WORD", 2),
unit("数据单元", "BYTE[]", mylength),
unit("校验码", "BYTE", 1)
];
function mylength(bytes) {
var b=bytes.substr(bytes.length-2,2);
return bytes.obj(b,"WORD");
}
var contentunits = [
unit("平台登入时间", "DATE2", 6),
unit("登入流水号", "WORD", 2),
unit("平台用户名", "STRING", 12),
unit("平台密码", "STRING", 20),
unit("加密规则", "BYTE", 1),
]
function received(bytes) {
//下面解析从服务器返回的数据
//console.log(bytes);
var data = bytes.parse(bytes, units);
console.log(data);
//data[6] = bytes.parse(data[6], contentunits);
}
var address = "mytcp://117.73.254.2:10828";
//如果不存在连接,就产生一个连接到服务器
if (!client.exist(address)) {
//产生新的连接(连接地址,解析单元定义,收到数据后执行函数)
client.new(address, units, received);
}
//发送的内容
var content = units.bytes(
contentunits, [now(), 1, "abcde", "123456", 0x01]
);
var data = [[0x23, 0x23], 0x07, 0xFE, "111111111111", 0x01, content.length, content, crc(content, 0, content.length)];
var bytes = units.bytes(units, data);
console.log(bytes.hex(bytes));
//下面发送指令到服务器上
client.send(address, bytes);
return 1;
模拟http协议连接
function received(bytes) {
//下面解析从服务器返回的数据
//console.log(bytes);
//var data = bytes.parse(bytes, units);
console.log("收到消息:" +utf8.string(bytes));
//data[6] = bytes.parse(data[6], contentunits);
}
var address = "tcp://127.0.0.1:511/11";
//如果不存在连接,就产生一个连接到服务器
if (!client.exist(address)) {
//产生新的连接(连接地址,解析单元定义,收到数据后执行函数)
var units=[
unit("头定义", "STRING", 0, utf8.bytes("\r\n\r\n")),
unit("消息体", "STRING", mylength)
]
function mylength(bytes) {
var header = utf8.string(bytes);
var items = header.split("\r\n");
for (var item in items) {
var mao = item.indexOf(":");
if (mao != -1) {
var name = item.substr(0, mao);
var value = item.substr(mao + 1);
if (name == "Content-Length") {
return int(value);
}
}
}
return 0;
}
client.new(address, units, received);
}
//发送的内容
var bytes1=utf8.bytes(
"POST /admin/setting.json HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/x-www-form-urlencoded\r\nConnection: Keep-Alive\r\nUser-agent: Mozilla/5.0\r\n\r\n"
);
//下面发送指令到服务器上
client.send(address, bytes1);