js构建实时应用程序的更好的方法是哪一种

js构建实时应用程序的更好的方法是哪一种

本文介绍了使用Angular.js和Node.js构建实时应用程序的更好的方法是哪一种?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Angular.js和Node.js的初学者,但是我意识到,有两种可能的方法可以制作实时应用程序.第一种是使用Socket.io,另一种是将RESTful与setInterval()函数一起用作客户端解决方案.我使用这两种选择构建了我的应用程序,但我不知道为什么最好使用一种替代另一种.

I'm beginner in Angular.js and Node.js, but I've realized that there are two possible ways to make real-time applications. The first is using Socket.io and the other is using RESTful with setInterval() function as a client-side solution. I built my application using both alternatives, but I don't know why it is better to use one instead the other.

我的控制器使用Angular.js(Socket.io替代品):

My controller using Angular.js (Socket.io alternative):

function MyController($scope, socket) {

  socket.on('test', function(data){
    $scope.data = data;
    console.log($scope.data);
  });

}

我的控制器使用Angular.js(RESTful替代):

My controller using Angular.js (RESTful alternative):

function MyController($scope, $http) {

  setInterval(function() {
    $http.get('/test.json')
         .success(function(data, status, headers, config) {
           $scope.data = data;
           console.log($scope.data);
         });
  }, 1000);

}

这些做事方式之间有什么区别?预先感谢!

What would be the differences between these ways of doing things?Thanks in advance!

推荐答案

如果您想要一个完全实时的Web应用程序,则可以使用套接字. Socket.io或SockJS都是非常好的客户端.但是,当不支持Web套接字时,它们可以正常降级.您可以选择要使用的传输方式.

If you want a fully real-time web application, then sockets are the way to go. Socket.io or SockJS are both extremely good clients. They have the ability to degrade gracefully when web sockets aren't supported, though, you may choose which transportation method you'd like to use.

您必须构建数据订阅服务,才能在所有用户之间传播更改. Tower.js和Meteor都使用反应式方法,并且在模型更改时使用事件侦听器.根据您想要此功能的复杂程度或功能的强大程度,它们将是可用的不同实现.

You'll have to build a data subscription service for changes to be propagated between all users. Tower.js and Meteor both use a reactive approach, and they use event listeners on model changes. Depending on how complex, or how powerful you want this feature, they'll be different implementations available.

当尝试在一次连接的许多用户之间同步客户端和服务器端数据时,它的确变得越来越复杂.我建议您看一下这两个框架,看看它们是如何工作的,并可能复制其中的一部分或全部功能.

It does become increasingly more complex when trying to sync client-side and server-side data across many users connected at once. I'd suggest you take a look at those two frameworks, see how they work, and possibly replicate parts of it, or all of it's functionality.

这篇关于使用Angular.js和Node.js构建实时应用程序的更好的方法是哪一种?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:40