何时使用socket.io和何时使用ajax [英] When to use socket.io and when to use ajax

查看:98
本文介绍了何时使用socket.io和何时使用ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在nodejs中进行了编程,看过如何使用socket.io和ajax对节点服务器的调用。 socket.io是否被替换为ajax?我很好奇知道在哪种情况下使用socket.io是好的,哪些是更好的ajax。感谢您的输入。

解决方案

嗯,网络套接字(通过socket.io)的主要之一是提供ajax缺少服务器推送因此,如果您想了解服务器上的新事件(例如不同用户向您发送消息)ajax,则需要执行服务器轮询,这意味着您可以在相对频繁的周期性循环中发送ajax请求。大多数时候服务器响应没有什么新的,但有时候有新的东西,客户端可以了解它。



Web套接字允许服务器主动推送通知客户,无轮询。因此,如果您的应用程序具有任何需要在服务器上启动并且仅在浏览器中显示的信息,那么Web套接字就是更好的解决方案。




  • 在请求/响应模型中将数据提交到服务器

    • ajax或web套接字基本上相同,传统形式POSTS也可以


      • 在事件流模型中将事件提交到服务器

        • web套接字是最好的,可以通过ajax进行仿真


      • 将事件从服务器推送到浏览器

        • 网络套接字是最好的,可以通过ajax长轮询,闪存等(如果真实的网络套接字不可用,socket.io有几个后备可以尝试使用)。


      • 旧版浏览器,一些移动平台

        • web套接字支持不在,所以ajax是你的后备



      I have been programming in nodejs have looked at how to use both socket.io and ajax calls to the node server. Is socket.io designed to replace ajax? I am curious to know in which cases it is good to use socket.io and which ones ajax is nicer. Thanks for the input.

      解决方案

      Well, one of the main thing web sockets (via socket.io) provides that ajax lacks is server push. So with ajax if you want to find out about new events on the server (a different user sent you a message, for example), you need to do server polling, meaning you send ajax requests in a relatively frequent periodic loop. Most of the time the server responds that there's nothing new, but occasionally when there is something new, the client can learn about it.

      Web sockets allow the server to actively push notices to the client without polling. So if your application has any kind of information that needs to start on the server and just show up in the browser, web sockets are a better solution there.

      • Submitting data to the server in request/response model
        • ajax or web sockets essentially equivalent, traditional form POSTS also OK
      • Submitting events to the server in an event stream model
        • web sockets are best, can be emulated via ajax somewhat
      • Pushing events from server to browser
        • web sockets are best, can be emulated via ajax long polling, flash, etc (socket.io has several fallbacks it can try to use if real web sockets are not available).
      • older browsers, some mobile platforms
        • web socket support is not there, so ajax is your fallback

      这篇关于何时使用socket.io和何时使用ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆