我有一台设备,其api文档说明以下几点:
1. Use websocket protocol to communication,the websocket version is RFC6455 13,The default listen port is 7788,no TLS encrypt.
2. The data format use Json.you can use javascript to Serializer and Deserialize very easy.
3. All the key value of json use lower-char.the name or all chinese char use UTF8 encoded.
我正在创建nodejs应用程序作为此设备的服务器。
var net = require("net");
var server = net.createServer();
server.on("connection",function(socket){
socket.on("data",function(d){
console.log("Data from %s : %s", remoteAddress,d);
socket.write(
{
"cmd":"getuserlist",
"stn":true
}
);
});
});
server.listen(9000,function(){
console.log("Server listening to port %j", server.address());
});
正在连接设备。连接后,我正在将json数据发送到设备,并且根据文档,它还需要响应json数据,但是它不起作用。请帮助我获得答复。此外,我需要通过解析json响应来调用URL。让我说清楚。
//If i get response like:
success:{
"count":40,
}
//I need to call an url like:
"http://example.com/40/"
我该如何实现?
附注:我是node.js的新手
答案 0 :(得分:1)
上面提供的代码有几个问题:
remoteAddress
从未声明,但在日志语句中使用了
socket.write
仅接受字符串参数,因此您需要先对JS对象进行字符串化处理
您已指定需要在连接后将JSON数据发送到客户端(设备),但实际上是作为对客户端请求的响应发送的。
7788
”,但您的服务器正在监听端口9000
websocket-s
而不是tcp-sockets
。带有TCP套接字的示例:
const net = require("net");
const server = net.createServer();
server.on("connection", function(socket) {
const remoteAddress = socket.remoteAddress;
socket.write(JSON.stringify({
cmd: "getuserlist",
stn: true
}));
socket.on("data", function(d) {
const data = JSON.parse(d);
console.log("Data from %s : %j", remoteAddress, data);
if (data.success && data.success.count == 40) {
// TODO: Call an url ...
}
});
});
server.listen(7788, function() {
console.log("Server listening to port %j", server.address());
});
您可以使用telnet
$ telnet localhost 7788
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
{"cmd":"getuserlist","stn":true}
{"success": {"count": 40}}
带有网络套接字的示例:
npm i -S ws
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 7788 });
wss.on('connection', function (ws, req) {
const remoteAddress = req.connection.remoteAddress
ws.send(JSON.stringify({
cmd: "getuserlist",
stn: true,
}));
ws.on('message', function (d) {
const data = JSON.parse(d);
console.log("Data from %s : %j", remoteAddress, data);
if (data.success && data.success.count == 40) {
// TODO: Call an url ...
}
});
});
您可以使用wscat
(或telnet
)测试网络套接字服务器。
npm i -g wscat
$ wscat -c ws://localhost:7788
Connected (press CTRL+C to quit)
< {"cmd":"getuserlist","stn":true}
> {"sucess": {"count": 40}}