Keep a web app running in the background - javascript

I'm developing a web app using Intel XDK. The web app shall get receive data from a server. I want to keep the app running always in the background and connected to a server listening for messages. On receiving a message from the server, it shall send a notification. Can I even keep a web app running like that? If yes, how?
To be clear, I don't want to know how to get the data, but instead I want to know how to constantly keep it checking for data from server.

Websockets or Socket.io library. You don't need keep checking new data from server, a server will tell you when a new data arrives

Related

How to listen to changes in background (Parse Server)

The task I want to accomplish is the following: Change some fields in the Parse dashboard and make the app respond right after. So pretty much make the UI respond to a change in the server.
After searching for a while, I see that I should set it up through Parse Cloud Code and use methods like afterSave. But as of now, I understand how to listen to an object being saved. How should I manage to do it the opposite way, which is the app listen to a change in the server? I will be manually changing some variables in the Parse Dashboard and I want the user to be able to get it whenever I manually change it. I could set up a timer (as a method inside the app’s code) and check it from the server in a 5 seconds interval but that would be pretty much inefficient in terms of requests, internet data.
You have few solution choice.
I dont know your architecture and your technologies what you use but I wrote two solutions.
silent notification with push server:
You need a push server on backend and you can send a silent push to frontend when the afterSave code triggering. However frontend code should be subscribe your push server.
e.g.: https://justmarkup.com/log/2017/02/implementing-push-notifications/
websocket communication:
You need a socket server on backend and a socket client on frontend and if you have a channel then you can send a message to client from server.
e.g.: https://blog.idrsolutions.com/2013/12/websockets-an-introduction/
I hope It will be help you.

Real Time Interaction on Web Page

Background: I have a microcontroller ESP8266 that enable connexion through TCP/IP, UDP or even HTTP stack using WiFi. A button is connected to this microcontroller and trigger event on touch. I send that information (now in UDP for test) towards a computer which runs an HTML carousel (web page). I would like to create the interaction between the button and the web page in real-time. I found that a simple HTML/CSS/JS web page doesn't allow to read UDP socket so I install a web server on the computer to use PHP.
NB: Real-time means direct interaction (inferior to 30 ms up to 100 ms) but should be ok in the actual data flow.
Problem: I struggle on the Web implementation. I found appropriate carousel in HTML/CSS/JS. I already received some UDP packet in a PHP file but I don't know how can I perform a real-time interaction (trigger image change in the carousel). I read about Ajax but it seems to be at client-side. I have in fact no background in Web application design.
I would like to know if in fact, it is possible and if yes basic information to start working on it.
Although I don't completely understand your microcontroller setup I can tell you that it is defiantly possible to change html elements and values in real-time. The place where I work uses Angular.js and it has a handy "scope" variable that is directly linked to the HTML. So, if the value in the code changes it will change on the website as well (without reloading the page). Its relatively simple to begin with but check out demos or something first, maybe I understand the question wrong.
https://angular.io/
Yes, this is definitely possible. Your two options are polling and websockets. If your backend is PHP, I'd start by writing some JavaScript to to poll the server at a given URL every 200 ms. Your PHP code handing that URL endpoint would then read a value from a data store somewhere, let's say a cache key in memcached.
Press button
UDP message sent
PHP code receives UDP message and sets value in cache key
When your polling code runs next it will receive the updated data which you can then display on your webpage.
This is a really basic (and inefficient) setup, but it's simple and should get you started.
We struggled with this same problem and eventually used NGINX and the PUSH module.
It allows a Post message to the server (NGINX) to be pushed to displayed web pages on the browser.
In our setup the controller sends a POST,containing JSON data, to a small linux board running NGINX. NGINX then sends this to any subscribers. The web page contains a couple of lines of js code to subscribe to the feed. When the JSON arrives at the page, it fires the js receiving code, and we update the displayed fields in the webpage. The setup is quite responsive, without measuring the delay, it seems to be within 60ms.

Cordova - How to make an online app/game with a Node.js server

I've been studying node.js for a while and now want to transition to connecting to my node.js server with my cordova app.
Wherever I look, I can't seem to find any real answers or tutorials.
If I go to myIP:8080 with my phone, it connects to the server, but how would I do it with a cordova app? Everything I try that's even remotely close I end up with a bunch of errors. Guide me please. I'm confused :/
P.S I initially tried making a game using a send/receive XMLHttpRequest() with PHP/MySQL, code worked but extremely laggy.. had to find out the hard way that it is not the way to go
You can do that using Socket.io with Nodejs to get real time data from all clients.
You app will connect to your server app which will be hosted somewhere. If you are running server code on localhost (on your computer or desktop) you need to expose this using some service like ngrok. Your app will send player coordinates to server which will broadcast those coordinates to all clients/players and same for all players. If still you need any help, let me know.
In you client app, in html page load this script, not exactly but similar, it will create a socket connection (duplex connection) between your app and server app. Then you will send your coordinates to server app using socket.emit().
<script>
var socket = io('server ip');
$('#button').click(function(){
socket.emit('coordinates', {x: 1, y: 2});
});
// server can send you different events/data
// 'moved' can be any event, its name can be 'abc'
socket.on('moved', function(data){
// process this data
});
</script>
Here are some resources.
http://socket.io/
https://github.com/techpines/express.io

Send message from Node.js Server to Client via function call

I want to send messages from my server to my client when a function is called. Using the code from this answer messages can be successfully sent from Server to Client every second.
I am building an application that runs node in the background, ideally I would like to be able to click a button that will call a function in the node server.js file which takes a parameter and sends that message to the client. The function in question would look like this
function sendToClient(message) {
clients[0].emit('foo', msg);
}
This would send the passed in message to the first client. How can I go about this?
In terminal, after you run node server.js is there a way to call a function from the server file using terminal, this could be a possible solution if so.
The best way to send messages from server to client right now is using webSockets. The basic concept is this:
Client A loads web page from server B.
Client A runs some javascript that creates a webSocket connection to server B.
Server B accepts that webSocket connection and the socket stays open for the duration of the life of the web page.
Server B registers event handlers to handle incoming messages from the web page.
Client A registers event handlers to handle incoming messages from the server.
At any point in time, the server can proactively send data to the client page and it will receive that data.
At any point in time, the client may sent data to the server and it will receive that data.
A popular node.js library that makes webSocket support pretty easy is socket.io. It has both client and server support so you can use the same library for both ends of the connection. The socket.io library supports the .emit() method mentioned in your question for sending a message over an active webSocket connection.
You don't directly call functions from client to server. Instead, you send a message that triggers the server to run some particular code or vice versa. This is cooperative programming where the remote end has to be coded to support what you're asking it to do so you can send it a message and some optional data to go with the message and then it can receive that message and data and execute some code with that.
So, suppose you wanted the server to tell the client anytime a temperature changed so that the client could display in their web page the updated temperature (I actually have a Raspberry Pi node.js server that does exactly this). In this case, the client web page establishes a webSocket connection to the server when the page loads. Meanwhile, the server has its own process that is monitoring temperature changes. When it sees that the temperature has changed some meaningful amount, it sends a temperature change message to each connected client with the new temperature data. The client receives that message and data and then uses that to update it's UI to show the new temperature value.
The transaction could go the other way too. The client could have a matrix of information that it wants the server to carry out some complicated calculation on. It would send a message to the server with the type of calculation indicated in the message type and then send the matrix as the data for the message. The server would receive that message, see that this is a request to do a particular type of calculation on some data, it would then call the appropriate server-side function and pass it the client data. When the result was finished on the server, it would send a message back to the client with the result. The client would receive that result and then do whatever it needed to with the calculated result.
Note, if the transactions are only from client to server with a response then coming back from the server, a webSocket is not needed for that type of transaction. That can be done with just an Ajax call. Client makes ajax call to the server, server formulates a response and returns the response. Where webSockets are most uniquely useful is if you want to initiate the communication from the server and send unsolicited data to the client at a time that the server decides. For that, you need some continuous connection between client and server which is what a webSocket is designed to be.
It appears there may be more to your question about how to communicate from a C# server to your node.js server so it can then notify the client. If this is the case, then since the node.js server is already a web server, I'd just add a route to the node.js server so you can simply do an http request from the C# server to the node.js server to pass some data to the node.js server which it can then use to notify the appropriate client via the above-described webSocket connection. Depending upon your security needs, you may want to implement some level of security so that the http request can only be sent locally from your C# server, not from the outside world to your node.js server.
In order to send a command to a client via the console there are two options, single process or multiprocess:
Single Process
When the command is run from console, temporary socket.io server starts listening on a port.
Once the client connects, send the message to the client.
Disconnect and stop the console app.
The reason this works is that socket.io clients are always trying to connect to the server. As long as the browser is open, they will try to connect. So even if the server only comes on for a few seconds, it should connect and receive messages. If the client is not running then simply create a timeout that will stop the console app and inform the user that it failed to broadcast the command.
While this approach is very easy, it's not robust nor efficient. For small projects this would work, but you'll have better luck with the next approach:
Multi-Process
This approach is much more reliable, expandable, and just better looking when you are talking about architecture. Here's the basic summary:
Spin up a stand-alone server that connects with clients.
Create a very similar console node app that will send a message to the server to forward on to clients.
Console app completes but the main server stays up and running.
This technique is just interprocess communication. Luckily you already have Socket.IO on the primary server, so your console app just needs to be another socket.io client. Check out this answer on how to implement that.
The downside to this is that you must secure that socket communication. Maybe you can enforce it to just allow localhost connections, that way you need access to the server to send the run command message (you absolutely don't want web clients executing code on other web clients).
Overall it comes down to the needs of your project. If this is a quick little experiment you want to try out, then just do it single process. But if will be hosting an express server (other webservers are available) and need to be running anyways, then multi-process is the way to go!
Example
I've created a simple example of this process using only Socket.io. Instructions to run it all are in the readme.
Implementations
In order to have C# (app) -> Node.js (server) -> Browser (client) communication then I would do one of the following:
Use redis as a message queue (add items to the queue with the app, consume with the server, which sends commands to client).
Live on the wild side and merge your NodeJS and C# runtimes with Edge.js. If you can run NodeJS from C# you will be able to send messages from your app to the server (messages are then handled by the server, just like any other socket.io client-server model).
Easier, but still kinda hacky, use System.Diagnostics.Process to start a console tool explained in the Multi-Process section. This would simply run the process with arbitrary parameters. Not very robust but worth considering, simple means harder to break (And again, messages are then handled by the server, just like any other socket.io client-server model).
I would create a route for sending the message and send message from post parameter. From CLI you can use curl or from anywhere really:
app.get('/create', function(req, res) {
if( data.type && data.content && data.listeners){
notify( data );
}
});
var notify = function( notification ){
ns_mynamespace.in(notification.listeners.users)
.emit("notification", {
id: notification.id,
title: 'hello', text: notification.content });
}
}

Android running browser ASP page that sends commands to windows PC

I am wondering how i can send a command (like 1, 2, 3..etc) from my web app (classic asp/asp.net) web page on my android web browser to a windows computer thats on the same LAN network. Kind of like an instant messenger type of thing so that i can design a web page with buttons and each button would send a command back to the computer.
Is that possible? Or do you know any other alternatives to accomplish this same task?
David
If you are looking at using a web server for each system windows system, then the android app simply calls some webpage with the message. The android app would need to keep calling a particular page for 'new' messages using an ajax request. However there are probably other better was of doing this - but it is possible using this method. Another option is each windows system self hosts their own WCF app which receives messages. You still need some central store to make sure all members get the messages unless they constantly poll each other.
Another alternative (and doesn't require polling) is to utilize sockets and simply stream the data back and forth over a port and keep the connection open.

Categories

Resources