I'm using node to make an email client. I want to update the browser window as soon as any new email arrives. I'm already fetching the emails on server side using mail-listener2. I want to push that data to client side. How do i do that?
Look at using websockets to push data in realtime to the client (browser). I would recommend using http://socket.io. They have some really great demos on there to show how you would do something like this.
Your server would send socket.io messages called message, containing the message details as JSON. Your client would listen for message events and update the UI as they come in.
Related
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.
We're in a project with a few microservices.
We've got a microservice (A) that get's and saves data and publishes a message to RabbitMQ, stating new data has come in (with the CouchDB _id), so that another microservice(b) can process it.
The problem lies in a third service where we've got a frontend that needs to be updated in 'real-time'.
We're using Socket.io for the client updates, but the node.js instance get's the updates from A as well.
The later is as followed:
- RabbitMQ message comes in
- Order is being retrieved from A (HTTP Request)
- Data is processed (remapping for user interface, bla bla bla)
- Data is sent through Socket.io to the client.
My problem is, how do I do this cleanly in node?
I want to split the files (ofcourse), make each their own module and create a handler which 'knows' RabbitMQ and Socket.io, so it can process the data and send a message back up the queue when the client has done something with the data that needs to be processed and the other way around.
If more info is needed, please tell me.
take advantage of your web server in between RabbitMQ and Socket.io.
When a message is done processing and ready to be delivered to the user, the web server can use socket.io to check if the user is online. if they are, send the message to the user. if they are not currently connected to socket.io, store the message in a database.
when the user reconnects, check the database to see if there are any messages waiting for that user and send them at that point.
I'm currently starting working with node.js and as a first little project have decided to code a little chat application. I am using socket.io and have followed the chat tutorial on http://socket.io/get-started/chat/ so far. Now I want to expand on the script, but I am stuck.
I fail to understand how (or if at all) socket.io is managing all connected clients on the server side. I can use the io.emit function to send a message to all connected users. But what if I want to send a message to one specific user?
I could of course "fake" it by sending the message to all clients and then on the client side check for an identifyer, etc. and only process the message if there is a match. But this would still send the message to everyone, and it could easily be circumvented by users with minimal JS knowledge.
The "filtering"/"targeting" needs to happen on the server side for security reasons. But I fail to see/understand how (or if at all) socket.io actually manages all client connections. Is there a way to get a list of all current connected clients? Can you interate over all connected clients in a loop? Can you assign custom identifiers/name to connections? And - as the practical application - can you then emit/send a message to a single connected user?
Every socket connection has a unique socket id assigned with it at the very first time when a new connection is established.You can emit the data using that particular id.
var socketId=socket.id;
socket.broadcast.to(socketId).emit("messageToReceiver",data);
Thus, you can send it to a particular person.
To get all the connected clients check this URL:
Socket.IO - how do I get a list of connected sockets/clients?
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 });
}
}
What would be best mechanism, for achieving ability, for users, that are logged in, receive messages, generated by server. As there is no way for a server, to send information to user, when it has new message to deliver, a user browser should poll with some specific interval, to receive in response new messages, additionally, there should be a way for server, to not send messages, that are already delivered to user. You could draw a connections with something like public chat mechanism, but the thing I need is message delay as close to realtime and ability to handle about 100 users simultaniously, making least traffic possible. Additional note: data is needed only when user is online, no need to store that data in server, for other users to read "history".
In my mind, there are one way of achieving this - global "message box" where server puts all messages, user browser is constantly polling the server, to check, if last received message ID is equal to last message ID in message box.
The question is, if this is right way to do that, or there are another ways for such tasks, as need for realtime data can be found everywhere: sensor data, multiplayer games, chat, stock market and more...
XEP-0124: Bidirectional-streams Over Synchronous HTTP (BOSH)
https://github.com/ssoper/jquery-bosh
Build a web-based notification tool with XMPP
Write real-time web applications with XMPP, PHP, and JavaScript
Hope this helps.
Isn't pushing a better strategy? Keep a tcp connection open between server and browser and stream changes to the browser when new information is available.
Take a look at html 5 websockets. (which does exactly this)
heres a demo
Have you looked at Comet?
Comet is a web application model in
which a long-held HTTP request allows
a web server to push data to a
browser, without the browser
explicitly requesting it.
If you search stackoverflow there is plenty of info about its use.