Real time updates with ASP.NET CORE and Angular2

2019-06-09 03:21发布

问题:

We are working on a project in ASP.NET CORE (server side) and Angular2 (client side).

We would like to achieve the functionality of real time updates. Eg if someone updates some values at server side, these changes are reflected on client side without the user having to refresh the page (the same functionality that eg Meteor establishes out of the box).

I thought that RXJS could do this job, however I can achieve this functionality with RXJS, I have to poll the server for changes. Since this will cause unneeded load at the server (even when caching is enabled) I don't really like this option.

So, I think there are better ways to achieve this functionality but I don't know which technologies to combine. For ASP.NET CORE, SignalR is not yet available so this is no option. Do I have to look into WebSockets, or what am I missing?

回答1:

If you don't require a bi-directional data binding between the server and clients and you are only interested in getting updates (I assume you will be changing the information using any RESTful API), SSE technology should work the best for you.

For client side implementation: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

For server side implementation using ASPNET Core check this great answer: ASPNET Core Server Sent Events / Response flush



回答2:

If you don't want to poll the server then you must use a permanent connection to the server to allow it to send updates to the client.

The best fitted technology for this task is a WebSocket, but you can use a page which doesn't finish and go flushing() data to the response.

For the second type, this will give you an idea on how to go, just use an ajax request and whenever you receive some data process it.

But again, better use WebSockets as they're designed for this type of task.