How to keep multiple views in Sync if I am viewing website on phone, PC, Tablet same time?

StackOverflow https://stackoverflow.com/questions/23657566

  •  22-07-2023
  •  | 
  •  

문제

I have a node.js Express app which is basically just a single slider. I want to be able to control the slider from my phone and have it updating on the computer screen in realtime..

At the minute the site opens up on all devices and they can all move the slider but the views aren't updating in realtime..

도움이 되었습니까?

해결책

You could use long polling.

The "computer screen" app registers a long poll connection with your node.js server.

// This example uses JQuery

function longPoll() {
    $.ajax({ url: "server", success: function(data){
        // update your view
    }, dataType: "json", complete: poll, timeout: 30000 });
};

The "phone" app sends a GET request to server that passes it through the open long poll connection to the "computer screen" app.

Each time the "computer screen" app receives a reply it will have to open a new long poll connection.

Search for long polling or Comet for more information.

Another solution would be using websockets. Node.js has several websockets libraries that can be used.

Using Socket.IO

Server side:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.emit('connected', true);
  socket.on('onScroll', function (data) {
    console.log(data);
  });
});

Client side:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('connected', function (data) {
    socket.emit('onScroll', { delta: x });
  });
</script>

Here is an example using express and Socket.IO to build a chat service

http://code.tutsplus.com/tutorials/real-time-chat-with-nodejs-socketio-and-expressjs--net-31708

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top