Read from DataOutputStream in NodeJS - node.js

I was wondering if there is a way to read from a stream the same way that the DataInputStream in java does?
I need this for two applications I am writing. One, written in Java, sends data using a DataOutputStream.
Something like this:
The Java client.
public static void main(String[] args) {
DataOutputStream out = ...;
out.writeByte((byte) 1);
}
The NodeJS server.
var net = require('net');
net.createServer(function (socket) {
socket.on("data", function (data) {
// Some way to read this?
}
}).listen(4444, '127.0.0.1');
I would like to add two bits of information:
No I am not sending just one byte, I am all the different types supported by the DataOutputStream.
I cannot change the method I am sending the data, I would like to find out how to use this.

In your socket.on() event, the data in the parenthesis is the output.
This should be your code.
var net = require('net');
net.createServer(function (socket) {
socket.on("data", function (data) {
var output = data.toString()
console.log(output)
}
}).listen(4444, '127.0.0.1');
If there are any errors, reply :D
Have a nice day

Related

The behaviour of standard input's readable event in Node JS

I wrote a UDP client to send lines from standard input to an UDP socket:
var PORT = 12000;
var HOST = '127.0.0.1';
var dgram = require('dgram');
var client = dgram.createSocket('udp4');
process.stdin.on("readable",
function() {
var chunk = process.stdin.read();
if (chunk !== null) {
client.send(chunk, PORT, HOST);
}
}
);
client.on("message",
function (message, remote) {
process.stdout.write(message);
}
);
Now, the readable event fires on the first time but stops working afterwards.
I successfully used this on a TCP chat client and server before: I got a readable event infinitely.
What could cause the problem here?
The code works if I subscribe to the data event on standard input. That fires every time I type a new line into the standard input.
See data event documentation at Stream class.

variable no longer in scope within a socket message fuction?

This is a file that listens to messages on port 5000.
The console.log(status) within the function listen seems to be printing true and false
However when exporting status to other files , I still get "none" instead of true and false ... Any suggestions?
var dgram = require('dgram');
var net = require('net');
var status="none";
var num=0;
var LOCAL_UDP_PORT=5000;
exports.listen=function(){
// TCP and UDP listeners
var sock = dgram.createSocket('udp4');
sock.on('message', function(msg, rinfo) {
try{
var obj = JSON.parse(msg);
if (obj.class == ".Announce") {
if(obj.dev.id == "BLA") {
status=true;
}
else
status=false;
}
console.log(status);
}
} catch(e){
// do nothing an err
}
});
sock.bind(LOCAL_UDP_PORT);
}
//Initialize
exports.status=status;
listen();
I guess the reason is, status take a string object, and when you do status=true/false, the reference changes, but exports.status would hold the original reference
try
var status={val:"none"};
...
status.val = true;
...
// in the module reading the value,
var status = status.val;
The incoming socket messages are asynchronous. That means they arrive sometime in the future. If you want to notify another module when they come in, then you will need to create a notification system and export the notification system so the other module can register an interest in getting notified.
You could create the notification system using an eventEmitter, using callbacks, using promises, etc... Why technique you choose would determine exactly what you would export and how the caller would register their interest.

nodejs xbee not receiving message

I want nodejs to send and receive messages with xbee. I know that the xbee setup works because I tested it on x-ctu. I tried the following but can't receive the message. It says it's open.
var util = require('util');
var SerialPort = require('serialport').SerialPort;
var xbee_api = require('xbee-api');
var C = xbee_api.constants;
var xbeeAPI = new xbee_api.XBeeAPI({
api_mode: 1
});
var serialport = new SerialPort("COM7", {
baudrate: 9600,
parser: xbeeAPI.parseRaw(1000)
});
serialport.on("open", function() {
console.log("open");
});
// All frames parsed by the XBee will be emitted here
//I think this is the problem
xbeeAPI.on("frame_object", function(frame) {
console.log(">>", frame);
});
I figured it out a few day ago. I relized I could just use serial port library.
You need to listen to the serial port first and then parse the data with xbee-api
serialport.on('data', function (data) {
try {
xbeeAPI.parseRaw(data);
} catch (e) {
console.error(e);
}
xbeeAPI.on("frame_object", function (frame) {
console.log(frame);
// do what do you want with the frame
}
}
You need to process the frame switch his frame.type, is case of ZIGBEE_RECEIVE_PACKET you need to convert data to string frame.data.toString(), i don't know why using API1 mode but please try to use 57600 baud-rate or higher to avoid the checksum mismatch problems Good luck.

flapjax get last element from eventstream

I am trying to implement a small chatservice using flapjax. I use an eventStream to get all the clients that connect to the server, and when broadcasting a message (the function on 'message') I map over this eventStream with the function that emits the message to the current client.
// Event stream yielding received clients
var clientReceiverE = receiverE();
// Event stream collecting all the clients
var clientsE = clientReceiverE.collectE([], function (client, clients) {return clients.concat([client]);});
socket.on('connection', function(client) {
clientReceiverE.sendEvent(client);
for (i = 0; i < chatMessages.length; i++) {
client.emit('message', chatMessages[i]);
}
client.on('message', function(message) {
chatMessages.push(message);
//for (i = 0; i < clients.length; i++) {
// clients[i].emit('message', message);
//}
mapE(clientReceiverE, function(client) {console.log(client); client.emit('message', message); return client});
});
client.on('nickname', function(name) {
});
});
The registring of the clients on the eventstream succeeds with this code, but the mapE doesn't result in a loop over all this clients. Does anybody know what is wrong here?
If you are still not guessed :) I think it's because mapE doesn't produce any action itself, mapE only creates and returns another EventStream which behaves like a given source, but with modified value by means of a given function.
You should not be using mapE like that. In your code you are attempting to recreate the mapE event bindings with each client.on('message', ...).
This problem is solved using a receiverE. This function is used to translate, external event streams into flapjax EventStream 's.
// Event stream yielding received clients
var clientReceiverE = receiverE();
// Event stream collecting all the clients
var clientsE = clientReceiverE.collectE([], function (client, clients) {return clients.concat([client]);});
var clientsB = clientsE.startsWith(undefined); //Turn the event stream into a behaviour (event + value)
var messagesE = receiverE();
messagesE.mapE(function(messagePacket){
var clients = clientsB.valueNow(); //Grab current value of client list behaviour
if(clients==undefined){
return;
}
var from = messagePacket.client;
for(var index in clients){
clients[index].emit('message', messagePacket.message);
console.log(messagePacket.message);
}
});
socket.on('connection', function(client) {
clientReceiverE.sendEvent(client);
client.on('message', function(message) {
messagesE.sendEvent({client: client, message: message});
});
});
The difference is this. The flapjax tree is isolated from the WebSocket event code and there is no shared state between them.

Writing data to a socket in Node

I'm getting a weird result when writing to a socket. I wrote a simple experiment with a client and a server:
server.js
var net = require('net');
net.createServer(function (connection) {
connection.on('data', function (data) {
console.log('data: ' + data);
});
}).listen(1337);
client.js
var net = require('net');
var client = net.connect({port: 1337}, function () {
var i = 0;
function send() {
client.write('a');
if (++i < 100) {
process.nextTick(send);
} else {
client.end();
}
}
send();
});
I expected the server to show 100 lines of data: a, but I ended up getting a smaller number of data: aaaaaaa lines. There's socket.setNoDelay() that seems to be what I want, but it doesn't seem to have any effect.
What am I missing?
Thanks a lot,
The TCP protocol only sends exactly the bytes you write in the socket. They will not be separated into messages, that's up to you. If you would like to get 100 lines of a then you would have to define 100 separate messages, and choose a delimiter for them. Usually people delimit messages sent to a TCP socket by \r\n.
So you would need to change your server to
var net = require('net');
net.createServer(function (connection) {
connection.on('data', function (buffer) {
var data = buffer.toString();
if (data.indexOf('\r\n') > -1) { // If there's more than one line in the buffer
var lines = data.split('\r\n'); // Split the lines
var i = lines.length;
while (i--) { // This will read your lines in reverse, be careful
console.log(lines[i]); // Print each line
}
} else {
console.log(data); // If only one line came through, print it
}
});
}).listen(1337);
And your client to
var net = require('net');
var client = net.connect({port: 1337}, function () {
var i = 0;
function send() {
client.write('a\r\n'); // Notice the \r\n part. This is what will help you separate messages on the server
if (++i < 100) {
process.nextTick(send);
} else {
client.end();
}
}
send();
});
And then I believe you would get 100 lines of a.
This module also provides a very interesting way to do it, and of course ZeroMQ would also shine in this because it already has a nice protocol that puts things in envelopes and sends them.
Also interestingly but out of the scope of your question, the messages you send write to the socket on one side will not arrive in the same order on the server. If you change your send function to
function send() {
if (++i < 100) {
client.write('a'+i+'\r\n');
process.nextTick(send);
} else {
client.end();
}
}
you can see them arriving not in the order you sent them.
By "The TCP protocol only sends exactly the bytes you write in the socket" I mean that if you do socket.write("1"); socket.write("2"), you will receive "12" on the server, because that's what you wrote on the socket. You have to explicitly separate your messages by something so that the server can know when a message starts and when a message ends.
About receiving things in order or not, you'll notice that if you remove the process.nexTick and have your client like:
var net = require('net');
var client = net.connect({port: 1337}, function () {
var i = 100;
while (i--) {
client.write('a'+i+'\r\n');
}
});
you'll get two messages on the server (at least I got): first numbers 83 - 99 and then 0 - 82, despite having wrote them in order.
Its because TCP splits it in packets in some magic way. The first package was actually larger than the second one, so it got there last. You can read more about how TCP works in the wikipedia page of course, and this video is probably going to say more than what you need to hear but its good to understand everything you're working with.

Resources