Should socket.io server update the database? - socket.io

I’m bulilding a web app that requires communication between clients. For this I’m using socket.io. Some data however has to be updated regularly in the database.
Some of them not that often (preferences, on button click) others in every second for example a timer value. This can not be calculated because the timer can be paused.
Right now whenever a client emits an event, it also makes a request to the backend to updated the database. I was wondering if it would be a good idea to have the socket.io server update the database so the clients would only have to take care of the socket communication? It seems to me that having the browser do a request to the backend is a bit resource heavy and takes out a bit from the advantages of the socket based communication
Edit: the back end of the app and the socket server are two different servers but physically they are on the same machine so their communication could be faster

the main point of using socket.io is that it allows you to push data to clients and clients do not need to check your server constantly to get the last changes, and providing a low-overhead communication channel between the server and the client.
you can call an API and also emit data and many other things on user click in your application.
it is a good idea to have the socket.io server update the database and you can also authorize each socket, save client sockets information and ...

Related

Should I use web sockets to pull data from server or just a flag and use that flag to send API request for data?

I am working on a project which is basically a Customer Feedback Analysis Dashboard. There are few graphs on the dashboard and data for each graph is fetched from the server through API requests.
Right now the dashboard is updated every time the page is refreshed. I want it to be updated immediately when there is a new feedback in the system. I am confused, whether I use websockets to send data for each graph or just a flag and use that flag to fetch data through API requests.
Like, facebook/twitter does. They tell you about new posts/tweets and when you click that button your feed/wall gets updated.
If you want to "push" data from server to client and you want that data to show up in a timely fashion (e.g. within 10-20 seconds of when it was available on the server), then you will want to implement some sort of "push" solution where the server can efficiently push data to the client whenever there is new data to send.
There are several possible approaches:
webSockets
socket.io
Server-sent events
Mobile platform-specific push (Android and iOS)
For a general purpose solution that works within a browser, you will want to use one of the first three. socket.io is built on top of webSockets (it just adds more features) so architecturally, they are similar.
Server-sent events are fairly new (modern browsers only) and are only for one way communication (from server to client). webSockets can be used for communication either way.
I'd personally recommend socket.io because of the features it offers (such as automatic client reconnection) and a simplified messaging layer. You can see the feature difference between socket.io and webSockets here. With socket.io, the client makes a connection to the server when the web page is loaded and that connection is persistent. After the connection is established, then either client or server can send messages to the other at any time in a very efficient manner.
Other useful references:
Push notification | is websocket mandatory?
websocket vs rest API for real time data?
Why to use websocket and what is the advantage of using it?
What are the pitfalls of using Websockets in place of RESTful HTTP?
Ajax vs Socket.io

Using SignalR to push to clients from a long running process

Firstly, here is state of my application:
I have a request coming in from a client (angularjs app) into my API (web api 2). This request is processed and a record is stored in a database. A response is then sent back to the client.
Currently, I have a windows service polling and processing this record(s).
Processing this record can be long running. As a side effect to processing this record, there might be notifications generated to be sent back to one or more clients.
My question is how do I architect this, such that I can utilise SignalR to be able to push the notifications back to the client.
My stumbling block:
I can register and store (in-memory backed by a db) the client's SignalR connectionid along with the application's own user identifier. This way I can match a generated notification with a signalr client.
At the moment, I'm hosting the SignalR hubs within the IIS process. So how do I get back from the Windows Service to IIS to notify the client when a notification is generated?
Furthermore, I should say I am already using SignalR elsewhere in the application and am using a SQL Server backplane.
The issue's with the current architecture:
Any processing is done in the same web request, and notifications are sent out via SignalR before a response to the client is returned. Luckily, the processing is minimal and very quick.
I think this is not very good in terms of performance or maintenance in the long run.
Potential solutions:
Remove SignalR hubs from IIS and host them somewhere else - windows service?
Expose an endpoint on the API to for the windows service to call to push the notification once a notification is generated?
Finally, to add more ingredients to the mix: Use a service bus to remove the polling component of the windows service, and move to a pub/sub architecture. Although this is more work than I want to chew off right now.
Any ideas/recommendations/constructive criticisms are welcome.
Thanks.
Take a look at this sample for starters
Another more advanced solution can be using a backplane to manage the communications between the front end and the backend...
HTH

The theory of websockets with API

I have an API running on a server, which handle users connection and a messaging system.
Beside that, I launched a websocket on that same server, waiting for connections and stuff.
And let's say we can get access to this by an Android app.
I'm having troubles to figure out what I should do now, here are my thoughts:
1 - When a user connect to the app, the API connect to the websocket. We allow the Android app only to listen on this socket to get new messages. When the user want to answer, the Android app send a message to the API. The API writes itself the received message to the socket, which will be read back by the Android app used by another user.
This way, the API can store the message in database before writing it in the socket.
2- The API does not connect to the websocket in any way. The Android app listen and write to the websocket when needed, and should, when writing to the websocket, also send a request to the API so it can store the message in DB.
May be none of the above is correct, please let me know
EDIT
I already understood why I should use a websocket, seems like it's the best way to have this "real time" system (when getting a new message for example) instead of forcing the client to make an HTTP request every x seconds to check if there are new messages.
What I still don't understand, is how it is suppose to communicate with my database. Sorry if my example is not clear, but I'll try to keep going with it :
My messaging system need to store all messages in my API database, to have some kind of historic of the conversation.
But it seems like a websocket must be running separately from the API, I mean it's another program right? Because it's not for HTTP requests
So should the API also listen to this websocket to catch new messages and store them?
You really have not described what the requirements are for your application so it's hard for us to directly advise what your app should do. You really shouldn't start out your analysis by saying that you have a webSocket and you're trying to figure out what to do with it. Instead, lay out the requirements of your app and figure out what technology will best meet those requirements.
Since your requirements are not clear, I'll talk about what a webSocket is best used for and what more traditional http requests are best used for.
Here are some characteristics of a webSocket:
It's designed to be continuously connected over some longer duration of time (much longer than the duration of one exchange between client and server).
The connection is typically made from a client to a server.
Once the connection is established, then data can be sent in either direction from client to server or from server to client at any time. This is a huge difference from a typical http request where data can only be requested by the client - with an http request the server can not initiate the sending of data to the client.
A webSocket is not a request/response architecture by default. In fact to make it work like request/response requires building a layer on top of the webSocket protocol so you can tell which response goes with which request. http is natively request/response.
Because a webSocket is designed to be continuously connected (or at least connected for some duration of time), it works very well (and with lower overhead) for situations where there is frequent communication between the two endpoints. The connection is already established and data can just be sent without any connection establishment overhead. In addition, the overhead per message is typically smaller with a webSocket than with http.
So, here are a couple typical reasons why you might choose one over the other.
If you need to be able to send data from server to client without having the client regular poll for new data, then a webSocket is very well designed for that and http cannot do that.
If you are frequently sending lots of small bits of data (for example, a temperature probe sending the current temperature every 10 seconds), then a webSocket will incur less network and server overhead than initiating a new http request for every new piece of data.
If you don't have either of the above situations, then you may not have any real need for a webSocket and an http request/response model may just be simpler.
If you really need request/response where a specific response is tied to a specific request, then that is built into http and is not a built-in feature of webSockets.
You may also find these other posts useful:
What are the pitfalls of using Websockets in place of RESTful HTTP?
What's the difference between WebSocket and plain socket communication?
Push notification | is websocket mandatory?
How does WebSockets server architecture work?
Response to Your Edit
But it seems like a websocket must be running separately from the API,
I mean it's another program right? Because it's not for HTTP requests
The same process that supports your API can also be serving the webSocket connections. Thus, when you get incoming data on the webSocket, you can just write it directly to the database the same way the API would access the database. So, NO the webSocket server does not have to be a separate program or process.
So should the API also listen to this websocket to catch new messages
and store them?
No, I don't think so. Only one process can be listening to a set of incoming webSocket connections.

How to send data to client browsers when a server side change occurs

I have an intranet based CRM application developed in CodeIgniter 2.1 where the application is running on a local Apache server and around 20 clients are accessing it over LAN. This is to be connected to a call center setup where the call center application (running on a separate server) will do a HTTP post with caller's number as well as terminal number of the agent where the call is arriving to a URL of my Codeigniter application. I am using this data to populate a database table of call records.
Now from the terminal number (each terminal has static IP, and a session in Codeigniter is linked to IP as well) I can find out which user (login session) of my application is about to receive the call. I want to find a way out how I can send data from server side (it will be regarding the call like the number who is calling, past call records etc.) to that specific user's browser via AJAX or something similar? The agent's browser needs to display this information sent from server.
Periodic polling from browser by jquery etc. is not possible as the data needs to be updated almost instantaneously and rapid polling up to this extent will lead to high CPU usage at client end as well as extra load on network.
P.S.: I only want to know how to modify the browser data from server end.
In AJAX, asynchronous request/response doesn't involve polling; there's just an open TCP connection and non-blocking I/O. The client makes a request but returns immediately; when the server sends the response, the client is notified. So you can achieve what you want with AJAX's XMLHttpRequest without polling[1]. All you need is a url from which to serve your notifications. You could have one request thread and a general dispatch method, or different urls and different threads for each, depending on how you needed to scale.
[1] Well, to be honest, with very little polling. You'd really need to establish what the session/global timeout was and reissue requests within that time limit.

Ajax vs Comet (not a chat application)

I've developed a web-based application in which a signed in user should send a message to the server telling he is still online every 3 seconds. The message is then processed by the server and a stored procedure is called in Mysql to set the user's status to online.
I've looked in to similar issues in which Comet and Ajax are compared (here or here) but considering that 3 second delay is acceptable and maximum users of 1000 are online in the system, is using Ajax a wise choice or Comet should be used?
For this kind of feature comet is more appropriate:
Your clients send messages (i'm online)
Your server broadcast the processed message (user X is still online)
In an ajax way you are only serving messages to server.
In order to get the "broadcast effect" in an ajax way. You will end up doing something similar to comet but with less efficient bandwidth.
Ajax:
Client send server - i'm in
Server process
Server send back to client list of user in.
In this case every client ask every 3 second the database for the COMPLETE "in" list.
In comet:
Client X send server - i'm in
Server process
Server send back to client S that user X is still online
In this case every client tell the server every 3 second that he is in.
The server send back to every connected client ONLY that x is still in
Comet is just the technique to broadcast back and push messages to client
Ajax is the technique to push client information to the server without having to refresh all the page.
Quoting wikipedia:
http://en.wikipedia.org/wiki/Comet_%28programming%29
Comet is known by several other names, including Ajax Push, Reverse Ajax , Two-way-web, HTTP Streaming,and HTTP server push among others.
So go comet :)
If you do not broadcast anything, then simple Ajax is the best option
In this particular case, since you do not need to send any information from the server to the client(s), I believe Ajax is the more appropriate solution. Every three seconds, the client tells the server it is connected, the database is updated, and you're done.
It could certainly be done using Comet, in which case you would basically ping each registered client to see if it is still connected. But, you would still need to run a query on the database for each client that responds, plus you would still need the client to notify the server on its initial connection. So, it seems to me that Comet would be more trouble than it's worth. The only thing that might make sense is if you could ping each registered client and store the responses in memory, then once all clients have been pinged you can run one single query to update all of their statuses. This would give you the added bonus of knowing as soon as a client disconnects as opposed to waiting for a timeout. Unfortunately, that is beyond the scope of my expertise with Comet so, at this point, I can't help to actually implement it.

Resources