Trigger a javascript function from nodejs backend - javascript

I'm building an interactive aplication for kids. I'm working with some sensors that sends UDP data and I need to do something with that on screen.
I want to work with node js in order to receive these udp commands (that's fine for me). The problem is that I can't find the way that node trigger some function to the frontend javascript vanilla. Is there a way to do that? I know I can comunicate java with node using post and emit, but for that, java must make the request first and wait for a concrete answer, in this case, frontend must be always waiting for node commands.
Thanks in advance!

It is possible to push from the server to the client if you first establish a connection using Websockets. The alternative approach is to frequently poll the server.
To use websockets, grab a library such as ws by using npm install ws and basically follow their docs. Example from their docs:
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});

Related

IOT tcp connection error with nodejs and net

I have created a server using net module:
// Creating and connecting with server
const net = require('net');
const server = net.createServer(); //Creating server
//Connecting with server
server.on('connection', function (socket) {
let remoteAddress = `${socket.remoteAddress},${socket.remotePort}`
console.log(remoteAddress)
console.log(`connection is established... ${Date.now()} \n `);
socket.write(`connection is established...${Date.now()} \n`);
//Receiving and Sending payload from/to client
socket.on('data', async function (payload) {
console.log("payload from client",payload)
socket.write(`acknowledge : ${payload}`);
});
//Close connection
socket.on('close', function () {
console.log('Server Connection Closed');
});
//Server error
socket.on('error', function (err) {
console.log("Caught flash policy server socket error: ")
console.log(err.stack)
});
});
server.listen(8001, function () {
console.log('Server Listing on Port 8001');
})
I deploy this code to AWS EC2 and When I tried to connect with telnet client (telnet ec2_ip 8001), initailly it is working but after sometime it is giving following errors.
screenshot of telnet client:
screenshot of ec2 logs:
And When I tried to connect with real IOT scooter with ec2 Ip address and port 8001, It is not connecting for even a second.
Can anyone please tell me what I am doing wrong?
Note: I don't have much knowledge about IoT. This is the first time I am connecting an IoT scooter with nodejs.
It is hard to know exactly what your problem is without seeing more of your code, or getting more explained. Like what happens in your real code? The logs seem to indicate that you are making outbound calls to another service after the initial connection. If that is the case, are you handling error conditions of your dependencies correctly? An unhandled exception would kill your server, and it would need to be restarted to work again. If you are using dependencies that fail, for instance databases, other servers, configuration files etc that fail on your scooter, that may be why it fails without even allowing one single connection. But without knowing more specifics about your application and architecture, it is just wild guesses at this point.
Your server example code, seems fine. As long as you have opened for traffic on that port in your routing configuration in AWS, it should respond. It could be that you just simply run out of connections, but again that requires me to know more to give you a definitive answer.
My advice would be to check your dependencies, and your logs for supporting systems.

Socket.io lost connection when phone locks react native

I have a simple application written in react native that uses a nodejs server connection with socket.io. My problem is that when the phone screen is locked the socket disconnects from the server. I need the always connected connection.
//server
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server,{
pingInterval: 20000,
pingTimeout: 10000,
});
//client mobile
const io = socket("http://192.168.0.20:3003");
It is difficult to continue socket.io connection on the lock screen.
(This is possible if you set a manifest that uses VoIP in the app)
I encountered the same problem and took action.
The countermeasure method was released to npm as "syncsocketio".
https://www.npmjs.com/package/syncsocketio
"syncsocketio" wraps socket.io.
"syncsocketio" was created with Typescript, but it can also be used with javascript.
Note that you need to use "syncsocketio" on both the server and client.
The npm page is in Japanese, but using the sample code is very easy to use.
Github also contains server and client test code, so check it out.
https://github.com/codianz/syncsocketio
I will be happy if it helps.

Execute NPM module through cordova

I created an app using cordova and everything is fine, expect I need to use a node module which doesn't have a client-side equivalent because I'm dealing with file write streams etc. I have found Cordova hooks to be my best shot so far, where I create an app_run hook to execute a node file that runs a socket server to listen for events from the client side.
I know, a very longwinded solution, but seems logically correct to me, the issue is that when I do create the server, building the app through Visual Studio 2017, the app launches on my android phone, but VS hangs on the "deploy" stage. I guess that it has to do with the event chain, so I created an asynchronous script like this:
(async function () {
const server = require('http').createServer()
const io = require('socket.io')(server)
io.on('connection', function (socket) {
console.log('heyo')
socket.emit('hello world', 'hi')
})
server.listen(3000, function (err) {
if (err) throw err
console.log('listening on port 3000')
})
})();
but this doesn't seem to work either, somehow VS hangs on "deploy". If anyone can possibly guide me in the right direction, that would be highly appreciated.
PS: I know the title is off, but every time I use StackOverflow to get help with a particular attempt, I'm told to do it another way, so I'll leave it open.
If the goal is to use socket.io in your cordova app, there IS a JS client for the web that you need to use and you don't need to use npm for that, just add a link to your client js file in your index file. (should be in a "client" folder when you init socket.io via npm).
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io('http://localhost');
</script>
https://socket.io/docs/client-api/

Why socketIO call too much connections?

I created my Socket server with Express, SocketIO and Redis
server.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(8890, function (e) {
console.log(e);
});
io.on('connection', function (socket) {
console.log("new client connected");
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, message) {
console.log("mew message in queue "+ message + "channel");
socket.emit(channel, message);
});
socket.on('disconnect', function() {
redisClient.quit();
});
socket.on('connect_error', function() {
redisClient.quit();
});
});
From command line, I run node server.js. Its worked.
I also created a html file to connect to that server.
From Browser Console, I run io.connect('http://localhost:8890'). I got as the result
As I see, too much connections (requests).
What happens? What wrong from my code?
You have mismatched client and server versions causing the initial connection to fail and the older client is dumb enough to just keep trying over and over again. If you are using 2.0.4 on the server, then you must use that version for the client too. If you serve the client version directly from your server with:
<script src="http://localhost:8890/socket.io/socket.io.js"></script>
Then, the socket.io server will automatically give you the right client version.
Or, you can manually link to the right version on your CDN such as https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js. But client and server versions MUST match.
The advantage of getting the client directly from your own server is that anytime you update your server version of socket.io, the client version will automatically be upgraded for you and kept in perfect sync since the matching client version is built into the server version.

making node.js net client

In all the examples of creating a client for node.js built-in net module I don't see how they get net to run on the client with out downloading it??
surely if my client-side code starts like this:
var net = require('net');
var client = net.connect({port: 8124},function(){
console.log('client connected');
client.write('world!\r\n');
});
then first i must write:
<script src="some strange node path to net ??"></script>
am i correct? how do I do this? btw: node.js is installed in my root on my server not local
I believe there's a bit of confusion here. The client example code you're showing is meant to run in node, not in the browser. That makes node a client of another (node or otherwise) TCP server.
If you want node to be the client and connect to another server over TCP, then run the code you're pasting. The net module is bundled with node, you're good to go.
If, however, you want your browser to talk to a node server then this would have to be over websockets (a streaming binary protocol over http, this is not plain-vanilla TCP). You would have to have a websockets module in the server, not plain net.
Just to be clear: net is simply node's interface to TCP sockets.

Categories