Server-side response without polling for changes

I'm experimenting with switching an existing web application with a knockout to js response.

At its core, the application establishes a connection with the server on the server and receives an asynchronous update (there may be many clients that can affect each other's state, for example, in a chat).

My question is: if I were playing the role of a rendering server, how could the changes be transferred to each client? I just started reading on server-side rendering, so I may not understand how this works, but as I suppose:

The client performs an action that is sent to the server, the server responds with an html fragment, which the client then replaces with the DOM

In the case of an application in which the state can be changed either by the server or by another client, will I still have to use websockets / http polling to display these updates?

Is it possible for the server to hit new fragments otherwise?

+4
source share
2 answers

With React, unidirectional threads are often the best way to do this. To achieve this, we must use an event emitter.

Get JSON from the server using websockets, SSE or polling (it doesn't matter). They must be in envelope format. This will be an example chat application.

{
  "type": "new-message", 
  "payload": {
    "from": "someone",
    "to": "#some-channel",
    "time": 1415844019196
  }
}

When you receive this message from the server, you send it as an event.

var handleMessage = function(envelope){
   myEventEmitter.emit(envelope.type, envelope.payload);
};

. , . ( ).

var MessageList = React.createClass({
   componentDidMount: function(){
      myEventEmitter.on('new-message', this.handleNewMessage);
   },
   handleNewMessage: function(message){
      if (message.to === this.props.channel) {
          this.setState({messages: this.state.messages.concat(message)});
      }
   },
   componentWillUnmount: function(){
      myEventEmitter.removeListener(this.handleNewMessage);
   },
   ...
});

, "user-new-message". , handleMessage, , , .

( ) .

html , . AJAX , , .

+7

, ?

, Sockets.

"". . , , . , .

, , , websockets/http polling ?

WebSockets, . WebSockets, , > . , WebSockets. , , AJAX . , .

, WebSockets, , .

0

All Articles