Bishal Chhetri
Bishal Chhetri

Reputation: 81

How to send json data to client from node js server?

I have a device that says following points its api documentation:

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.

I am creating nodejs app as a server to this device.

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());
});

The device is being connected. After connection i am sending json data to the device and according to the documentation it also needs to respond json data but it is not working. Please help me to get the response. Further i neeed to call to an url by parsing the json response. let me make clear.

//If i get response like:
success:{
  "count":40,
}
//I need to call an url like:
"http://example.com/40/"

How can i achieve it ?
P.S: I am new to node.js

Upvotes: 1

Views: 5656

Answers (1)

Ihor Sakailiuk
Ihor Sakailiuk

Reputation: 6058

There are couple of issues with the code provided above:

  • remoteAddress never declared, but used in the log statement

  • socket.write accepts only string arguments, so you need to stringify JS object before sending it

  • You have specified that you need to send JSON-data to the client (device) after the connection, but you're actually sending it as a response to the client's requests.

  • You've specified "The default listen port is 7788" but your server is listening on port 9000
  • And finally, you've specified that the communication protocol is websocket-s not a tcp-sockets.

Example with TCP-sockets:

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());
});

You can test the tcp-server using, for example telnet

$ telnet localhost 7788

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
{"cmd":"getuserlist","stn":true}
{"success": {"count": 40}}

Example with Web-sockets:

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 ...
        }
    });
});

You can test web-socket server using wscat (or telnet as well).

npm i -g wscat

$ wscat -c ws://localhost:7788

Connected (press CTRL+C to quit)
< {"cmd":"getuserlist","stn":true}
> {"sucess": {"count": 40}}

Upvotes: 3

Related Questions