我是node.js的新手,并尝试使用ProtoBuf,sails和socket.io与第三方守护程序建立Persistent Socket连接。
过去两周我在Stack Overflow和其他论坛中搜索过并发布此问题以获得您的宝贵回复。
情景:
在端口5001上运行第三方守护程序(同步),该守护程序应与客户端具有持久套接字连接。如果没有进行任何通信,该守护进程将等待30秒并关闭套接字。
我无法使用以下代码示例获取server.js与第三方守护程序之间的持久套接字连接(使用节点的网络API)。每次创建一个新的套接字ID,同时将EncryptRequest和UserRequest消息发送到第三方守护进程,因为server.js会创建新套接字,并且每次都连接到192.168.1.3:5001。
因此,我在server.js中将套接字初始化和连接移到了io.sockets.on(' connection',...)行之上。在这种情况下,我只建立了一个套接字连接(Persistent),但它在控制器上执行回调以多次运行。
a)我使用命令" sails new webgui"
创建了一个风帆应用程序b)我在webgui / api / controllers / SampleController上创建了一个控制器。 并且它的方法是getAuth(),它在webgui / config / routes.js中有一个路由条目
' /的WebGUI / AUTH':' SampleController.getAuth'
每当我输入http://mysamplehost.com:1337/webgui/auth时,它都会与第三方守护进程通话并获得响应。
c)第三方守护程序连接逻辑写入新的配置文件并存储在config / server.js中。 我正在使用风帆为PoC创建这个原型。
目前,SampleController.js是我的客户端。我现在没有使用任何HTML。
流程是:
Sails Application
----------------------------------------- -------------------
| mysamplehost on port 1337 | | |
| | | |
| ------------- ------------ | | |
| | Client | | HTTP | | Requires Persistent | 3rd Party |
| | | |Server | | Socket Connection | daemon running |
| | SampleCon | 8081 |running on| | on Port 5001 | on Port 5001 |
| |troller.js |<------>|Port 8081 |<------------------------>| |
| | | | | | | |
| | | | | | | |
| | | | server.js| | | |
| | | | | | | |
| ------------- ------------ | | |
| | | |
----------------------------------------- -------------------
如何使套接字变量&#39;客户端&#39;在config / server.js中持久连接第三方守护进程,没有多次执行回调(在SampleController.js中)的响应?
谢谢, 约杰什
var socket = require('socket.io-client')('http://192.168.1.2:8081',{'force new connection': true});
module.exports = {
getAuth: function(req, res) {
socket.binaryType = "arraybuffer"; // We are talking binary
var ProtoBuf = require("protobufjs");
var FPMessage = ProtoBuf.loadProtoFile("/webgui/api/protobuf/pb_common.proto").build("ProtoBuf.BaseMessage");
var pb_login_builder = ProtoBuf.loadProtoFile("/webgui/api/protobuf/pb_login.proto");
var EncryptRequest = pb_login_builder.build("ProtoBuf.EncryptRequest");
var EncryptResponse = pb_login_builder.build("ProtoBuf.EncryptResponse");
var UserRequest = pb_login_builder.build("ProtoBuf.UserRequest");
var UserResponse = pb_login_builder.build("ProtoBuf.UserResponse");
socket.on('connect', function () {
var msg = new EncryptRequest();
msg.device_id = "";
msg.msg_name = "EncryptRequest";
msg.type = "none";
socket.emit('message', msg.toArrayBuffer());
socket.on('myMsg', function (evt) {
try {
var msgName = FPMessage.decode(evt);
if(msgName.msg_name == 'EncryptResponse') {
var msg = EncryptResponse.decode(evt);
var hq_device_id = msg.device_id;
console.log("EncryptResponse - HQ Device ID : "+hq_device_id+"\n");
var msg2 = new UserRequest();
msg2.device_id = "";
msg2.msg_name = "UserRequest";
msg2.username = "Administrator";
socket.emit('message', msg2.toArrayBuffer());
}
else if(msgName.msg_name == 'UserResponse') {
var msg = UserResponse.decode(evt);
var hq_device_id2 = msg.device_id;
console.log("UserResponse - HQ Device ID : "+hq_device_id2);
socket.removeAllListeners();
return res.json(msg);
}
} catch (err) {
console.log("Error: "+err+"\n");
}
});
socket.on('disconnect', function () {
console.log("disconnected.");
});
});
}
};
var sails = require('sails'),
path = require('path'),
ProtoBuf = require('protobufjs'),
net = require('net'),
server = require('http').createServer(function(request,response){}).listen(8081),
io = require('socket.io').listen(server);
var HOST = "192.168.1.3";
var PORT = 5001;
var XD_HDR_LEN = 4; /* xtremed data header length (bytes) */
var client = new net.Socket();
var client_conn = client.connect(PORT, HOST);
client_conn.setTimeout(15000);
var builder = ProtoBuf.loadProtoFile(path.join(__dirname, "./../api/protobuf", "pb_common.proto")),
fpMessage = builder.build("ProtoBuf.BaseMessage");
server.on("listening", function(){
sails.log.info('Server started');
});
server.on("error", function(err) {
console.log("Failed to start server:", err);
process.exit(1);
});
io.sockets.on('connection', function(socket){
sails.log.info("New socket Connection - Socket id : "+socket.id);
socket.on("message", function(message) {
try {
var buf = addMessageHeader(message);
sails.log.info("Connected to: " + HOST + ":" + PORT);
client.write(buf);
} catch(err) {
sails.log.error("websocket message failed! ", err);
}
});
client_conn.on("data", function(data2) {
var data3 = stripMessageHeader(data2);
io.emit('myMsg',data3);
});
client_conn.on('close', function() {
sails.log.info('Connection closed');
});
socket.on("close", function() {
socket.disconnect();
//socket.removeAllListeners();
sails.log.info("Client socket closed." );
});
});
/* In: Buffer object
* Out: Buffer object
*/
function addMessageHeader(message)
{
var version = 1;
var options = 0;
var buf = new Buffer(message.length + XD_HDR_LEN);
//Message header: { u32 version:4, options:4, length:24; }
buf[0] = version; /* TODO: support options */
buf[1] = (message.length & 0xFF);
buf[2] = ((message.length & 0xFF00) >> 8);
buf[3] = ((message.length & 0xFF000) >> 16);
message.copy(buf, XD_HDR_LEN);
return buf;
}
/*
* In: Buffer object
* Out: Buffer object
*/
function stripMessageHeader(buffer)
{
/* note: slice uses existing buffer */
return buffer.slice(XD_HDR_LEN);
}