I am being new to node.js , coming from js background i have quite harder time to understand concept behind back end stuff, currently i am trying to create simple console chat. Code for server :
var net=require("net");
var sockets=[];
net.createServer(function(socket){
sockets.push(socket);
socket.on("data",function(data){
posliSpravu(socket,JSON.parse(data));
});
socket.on("close",function(){
console.log(socket + " has disconnected");
sockets.splice(sockets.indexOf(socket),1);
})
}).listen(8888);
function posliSpravu(from,message){
var msg=JSON.stringify("Niekto povedal : " + message)+'\n';
sockets.forEach(function(incoming_socket){
if(incoming_socket!=from){
incoming_socket.write(msg);
}
})
}
code for client
var net=require("net");
var client=new net.Socket();
client.connect(8888,function(){
console.log("Connected");
});
process.stdin.resume();
process.stdin.on("data",function(data){
posli(data);
})
client.on("data",function(data){
console.log("Recieved data === " + JSON.parse(data));
})
function posli(msg){
client.write(JSON.stringify(msg)+'\n');
}
When i am trying to send some message , it always outputs "Message recieved === [Object][Object]"
I tried to replace JSON.parse with JSON.strngify , but output was only some numer , propably test represented in ascii.
How can i fix it so it would display text i send<
"Message recieved === [Object][Object]"means you're trying to print objects as strings or that you attempted to send an object over the wire without stringifying it first. Try just printing the objects by themselves (not preceded by "Message received") and see what happens.readlinemodule with newline-terminated JSON strings/payloads.