Beginner Node.JS net.createServer example - javascript

I am an old PERL coder trying to learn node.JS programming. I have question about the code I am writing to create a socket connection between a server and a client app.
The code below works. But I do not know how to accept data sent from the client to the server.
Basically what I want to do is very simple. Client connects to a Server listening on a socket, sends some information, which the Server reads and then sends information back to the Client. The only part I am not understanding is how to get the Server side to read/accept/display the data string sent from the Client.
Can someone please point me in the right direction?
Thank you for your help in advance.
(My apologies for being ignorant.)
Here is the server side code:
var net = require('net');
var server = net.createServer(function(socket) {
// confirm socket connection from client
console.log((new Date())+'A client connected to server...');
socket.on('data', function(data) {
var json = JSON.parse(data.toString());
console.log(json)
});
// send info to client
socket.write('Echo from server: NODE.JS Server \r\n');
socket.pipe(socket);
socket.end();
console.log('The client has disconnected...\n');
}).listen(10337, '192.168.100.1');
Here is the client code:
var net = require('net');
var client = new net.Socket();
client.connect(10337, '192.168.100.1', function() {
console.log('Connected'); // acknowledge socket connection
client.write('Hello, server! Love, Client.'); // send info to Server
});
client.on('data', function(data) {
console.log('Received: ' + data); // display info received from server
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
I get an error on the server when I do this where it says the string sent from the client is an invalid token. here is the error message.
undefined:1
Hello, server! Love, Client.
^
SyntaxError: Unexpected token H
at Object.parse (native)
at Socket.<anonymous> (/root/nodejs/server-example.js:7:19)
at Socket.emit (events.js:117:20)
at Socket.<anonymous> (_stream_readable.js:765:14)
at Socket.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:427:10)
at emitReadable (_stream_readable.js:423:5)
at readableAddChunk (_stream_readable.js:166:9)
at Socket.Readable.push (_stream_readable.js:128:10)
at TCP.onread (net.js:529:21)

I was being stupid. I found the answer I was looking for. And it was very simple.
Here is what I should have written in place of the JSON statements
socket.on('data', function(data) {
var string = (data.toString());
console.log(string)
});

or handle both JSON and Strings that get written to the socket:
socket.on('data', function(data) {
try {
var obj = JSON.parse(data.toString())
console.log(JSON.stringify(obj, null, 4))
}
catch(e) {
var string = data.toString()
console.log(string)
}
})

Related

Cannot connect form javascript to a broker through tcp using mqtt.js

I would like to conenct an MQTT broker with Javascript in order to subscript to a topic and publish messages. The connection needs to be done through tcp on port 1883. I am using MQTT.js library. The front end is in angularjs.
The example followed is the one in MQTT.js page, though the connection cannot be achieved. Could anyone please help?
Connection through index.html:
<script src="../node_modules/mqtt/browserMqtt.js"></script>
Code for connection:
var client = mqtt.connect('url.com:1883',{clientId :'client1', clean: true});
client.on('connect', function () {
console.log("onsubscribe");
client.subscribe('votingSignals', function (err) {
if (!err) {
console.log("onsubscribe");
client.publish('votingSignals', 'start')
}
})
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
The error displayed is:
WebSocket connection to 'ws://url.com:1883/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
From a web browser you can ONLY use MQTT over Websockets, not native MQTT (over TCP).
This is because the browser will not let you open a normal socket.

secured connection between javascript client and python server

i have python server(with the help of asyncio and websockets module) and js client(with the help of websockets library) that are connected. The problem is that i need this connection to be secured (i'm working on passwords), but i had no success on establishing a connection with wss(web socket secure) - the code runs only with ws.
I even tried to establish my own encryption with RSA and AES but that also didn't work.
i'm really hopeles about it so if anyone ever did it or know a little about it, pls help me figure out what's wrong with it, or a direction to a rigth solution for secured connection that will work.
here's my server:
async def app(websocket, path):
while True :
data = await websocket.recv()
if (data== "close"):
print("connection with client closed.")
break
data = data.encode()
arr = data.split("~".encode())
for i in range(0,4):
arr[i]=arr[i].decode()
resualt=algo(arr)
await websocket.send(resualt)
start_server = websockets.serve(app, '0.0.0.0', 6169)
and my client:
var socket = new WebSocket("ws://127.0.0.1:6169/");
socket.onopen = function (evt) {
socket.send(st);
};
socket.onmessage = function (evt) {
alert("scrool extension page down to see the password");
$('#res').val(evt.data);
socket.send("close");
};
socket.onerror = function (evt) {
alert("the error is: "+evt.data);
};
in the python script we tried to use ssl:
c = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
c.load_default_certs(purpose=ssl.Purpose.CLIENT_AUTH)
start_server = websockets.serve(app, '0.0.0.0', 6169, ssl=c)
and in the js sciprt we wrote instead of the ws, wss:
"ws://127.0.0.1:6169/")
and the error we get:
WebSocket connection to 'wss://127.0.0.1:6169/' failed: Error in connection
establishment: net::ERR_CONNECTION_CLOSED

binaryjs client crashes when server restarts

I'm using binaryjs to implement a video transfer program between node.js server and node-webkit client.The client stays connected,once a video is uploaded,the client starts downloading it.
It works fine generally,the client does get the videos.But the client throws an error and crashes when the server restarts or crashes. I have been listening the BinaryClient 'error' & 'close' event,however it doesnot works.
I guess maybe i'd listen 'error' event from something else.What to do to fix the problem?Anyone can help?
Thanks a lot!
app.js:
var BinaryServer = require('binaryjs').BinaryServer;
var server = http.createServer(app).listen(3000);
var binaryServer = new BinaryServer({ server: server, path: '/binary' });
binaryServer.on('connection', function (client) {
// client on stream
// client on close
// client on error
});
// binaryServer on error
client:
var BinaryClient = require('binaryjs').BinaryClient;
var binaryClient = new BinaryClient('ws://127.0.0.1:3000/binary');
binaryClient.on('open', function () {
// binaryClient.createStream( ... )
});
// binaryClient on stream
// binaryClient on close
// binaryClient on error
error:
Uncaught node.js Error
Error: read ECONNRESET
at exports._errnoException (util.js:742:11)
at TCP.onread (net.js:541:26)

JavaScript secure token function: ECONNRESET

I was looking at this thread Secure random token in Node.js and tried to make a function:
var crypto = require('crypto');
function token() { // create a secure token
var token;
crypto.randomBytes(48, function(ex, buf) {
token = buf.toString('hex');
});
return token;
}
// more code...
var token = token();
It crashes:
Error: read ECONNRESET
at exports._errnoException (util.js:746:11)
at TCP.onread (net.js:559:26)
Any reasons to why?
"ECONNRESET" means the other side of the TCP conversation abruptly
closed its end of the connection. This is most probably due to one or
more application protocol errors. You could look at the API server
logs to see if it complains about something.

nodejs: Error: EADDRNOTAVAIL, Cannot assign requested address

I have the following node.js server running on 172.16.1.218:
var net=require('net');
var server = net.createServer(function (socket) {
socket.write("Echo server\r\n");
socket.pipe(socket);
});
server.listen(6001, "172.16.1.218");
I can telnet into it and it echos as expected.
I have the following node.js server running on 172.16.1.224:
var net = require('net');
var server = net.createServer(function (socket) {
// Every time someone connects, tell them hello and then close the connection.
socket.addListener("connect", function () {
sys.puts("Connection from " + socket.remoteAddress);
socket.end("Hello World\n");
});
});
// Fire up the server bound to port 7000 on localhost
server.listen(6001,"172.16.1.218");
But when I try to run it, I get the following error:
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: EADDRNOTAVAIL, Cannot assign requested address
at Server._doListen (net.js:1100:5)
at net.js:1071:14
at Object.lookup (dns.js:159:5)
at Server.listen (net.js:1065:20)
at Object.<anonymous> (/home/hynese/Desktop/test.js:16:8)
at Module._compile (module.js:402:26)
at Object..js (module.js:408:10)
at Module.load (module.js:334:31)
at Function._load (module.js:293:12)
at Array.<anonymous> (module.js:421:10)
I've turned off all firewalls, etc. I can't make any sense of this error. Hoping someone can help.
Many thanks in advance,
On 172.16.1.224 you cannot listen on 172.16.1.218 because that's not the IP of the machine you're listening on.
If you want to listen on that machine, use:
server.listen(6001,"172.16.1.224");

Categories

Resources