I am new to node.js and to it's environment so I am having problems when I want to make a server that listens for incoming data from a socket. The problem is I am having trouble working with streams in node.js. I listen for incoming data and usually i get 3-4 requests sent on the socket. The problem is I want to write and after that exit the code or something. How do I know when the client has finished sending all his data. I check for a size param in the json received now, but I am not sure if it is a good idea. Basically I want to handle all the data he sent and after that send 1 response, how I did it now it sends the same response many times.
This is a part of my code for example and testing purpose:
var server = net.createServer(function(sock) {
sock.on('data', function(data) {
var string = data.toString()
,json = JSON.parse(string);
if (json.size > 50) {
sock.write(JSON.stringify(
{"success" : "OK"}
);
}
});
});
var net = require('net');
var server = net.createServer(function(sock) {
sock.on('data', function(data) {
var json = JSON.parse(data.toString());
// Probably want to do something special here
});
sock.on('end', function() {
// Server disconnected
sock.write(JSON.stringify({ success: 'OK' });
});
});