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

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

问题描述

我一直在用 nodejs 编程,研究了如何使用 socket.io 和 ajax 调用节点服务器.socket.io 是用来替代ajax 的吗?我很想知道在哪些情况下使用 socket.io 好,哪些 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.

推荐答案

好吧,Web 套接字(通过 socket.io)提供的 ajax 缺少的主要内容之一是服务器推送.因此,使用 ajax,如果您想了解服务器上的新事件(例如,不同的用户向您发送了一条消息),您需要进行服务器轮询,这意味着您以相对频繁的周期循环发送 ajax 请求.大多数情况下,服务器会响应没有新东西,但偶尔有新东西时,客户端可以了解它.

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 套接字允许服务器主动向客户端推送通知而无需轮询.因此,如果您的应用程序有任何类型的信息需要在服务器上启动并仅显示在浏览器中,那么 Web 套接字是更好的解决方案.

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.

  • 以请求/响应模型向服务器提交数据
    • ajax 或 web sockets 本质上是等价的,传统形式的 POSTS 也可以
    • web sockets 是最好的,可以通过 ajax 模拟
    • 网络套接字是最好的,可以通过 ajax 长轮询、闪存等进行模拟(socket.io 有几个后备,如果真正的网络套接字不可用,它可以尝试使用).
    • 网络套接字支持不存在,所以 ajax 是你的后备

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

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