jQuery nodejs:Ajax 与 Socket.IO,优缺点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7193033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
nodejs: Ajax vs Socket.IO, pros and cons
提问by ezmilhouse
I thought about getting rid of all client-side Ajax calls (jQuery) and instead use a permanent socket connection (Socket.IO).
我想摆脱所有客户端 Ajax 调用 (jQuery),而是使用永久套接字连接 (Socket.IO)。
Therefore I would use event listeners/emitters client-side and server-side.
因此,我会在客户端和服务器端使用事件侦听器/发射器。
Ex. a click event is triggered by user in the browser, client-side emitter pushes the event through socket connection to server. Server-side listener reacts on incoming event, and pushes "done" event back to client. Client's listener reacts on incoming event by fading in DIV element.
前任。单击事件由用户在浏览器中触发,客户端发射器通过套接字连接将事件推送到服务器。服务器端侦听器对传入事件做出反应,并将“完成”事件推送回客户端。客户端的侦听器通过淡入 DIV 元素对传入事件做出反应。
Does that make sense at all? Pros & cons?
这样做有意义吗?优点缺点?
采纳答案by generalhenry
Sending one way messages and invoking callbacks to them can get very messy.
以一种方式发送消息并调用它们的回调会变得非常混乱。
$.get('/api', sendData, returnFunction);
is cleaner than
socket.emit('sendApi', sendData);
socket.on('receiveApi', returnFunction);
$.get('/api', sendData, returnFunction);
比
socket.emit('sendApi', sendData);
socket.on('receiveApi', returnFunction);
Which is why dnode and nowjs were built on top of socket.io to make things manageable. Still event driven but without giving up callbacks.
这就是为什么 dnode 和 nowjs 建立在 socket.io 之上以使事情易于管理的原因。仍然是事件驱动但不放弃回调。
回答by Nick Steele
There is a lot of common misinformation in this thread that is very inaccurate.
该线程中有很多常见的错误信息,这些信息非常不准确。
TL/DR;WebSocket replacesHTTP for applications! It was designed by Google with the help of Microsoft and many other leading companies. All browsers support it. There are no cons.
TL/DR;WebSocket替代应用程序的 HTTP!它是由谷歌在微软和许多其他领先公司的帮助下设计的。所有浏览器都支持。没有缺点。
SocketIO is built on top of the WebSocket protocol (RFC 6455). It was designed to replaceAJAX entirely. It does not have scalability issues what-so-ever. It works faster than AJAX while consuming an order of magnitude fewer resources.
SocketIO 建立在 WebSocket 协议 ( RFC 6455)之上。它旨在完全取代AJAX。它没有任何可扩展性问题。它比 AJAX 工作得更快,同时消耗的资源少一个数量级。
AJAX is 10 years old and is built on top of a single JavaScript XMLHTTPRequestfunction that was added to allow callbacks to servers without reloading the entire page.
AJAX 已有 10 年历史,它建立在单个 JavaScript XMLHTTPRequest函数之上,该函数被添加以允许在不重新加载整个页面的情况下回调服务器。
In other words, AJAX is a document protocol(HTTP) with a single JavaScript function.
换句话说,AJAX 是具有单个 JavaScript 函数的文档协议(HTTP)。
In contrast, WebSocket is a application protocolthat was designed to replace HTTP entirely. When you upgrade an HTTP connection (by requesting WebSocket protocol), you enable two-way full duplex communication with the server and no protocol handshaking is involved what so ever. With AJAX, you either must enable keep-alive (which is the same as SocketIO, only older protocol) or, force new HTTP handshakes, which bog down the server, every time you make an AJAX request.
相比之下,WebSocket 是一种旨在完全取代 HTTP的应用程序协议。当您升级 HTTP 连接(通过请求 WebSocket 协议)时,您启用与服务器的双向全双工通信,并且不涉及任何协议握手。使用 AJAX,您必须启用 keep-alive(与 SocketIO 相同,只是旧协议),或者每次发出 AJAX 请求时强制执行新的 HTTP 握手,这会使服务器陷入困境。
A SocketIO server running on top of Node can handle 100,000 concurrentconnections in keep-alive mode using only 4gb of ram and a single CPU, and this limit is caused by the V8 garbage collection engine, not the protocol. You will never, ever achieve this with AJAX, even in your wildest dreams.
运行在 Node 之上的 SocketIO 服务器仅使用 4GB 内存和单个 CPU就可以在 keep-alive 模式下处理 100,000 个并发连接,这个限制是由 V8 垃圾收集引擎引起的,而不是由协议引起的。即使在您最疯狂的梦想中,您也永远不会使用 AJAX 实现这一目标。
Why SocketIO so much faster and consumes so much fewer resources
为什么 SocketIO 速度如此之快,消耗的资源如此之少
The main reasons for this is again, WebSocket was designedfor applications, and AJAX is a work-around to enable applications on top of a document protocol.
造成这种情况的主要原因再次是,WebSocket 是为应用程序设计的,而 AJAX 是一种在文档协议之上启用应用程序的变通方法。
If you dive into the HTTP protocol, and use MVC frameworks, you'll see a single AJAX request will actually transmit 700-900 bytes of protocol load just to AJAX to a URL (without any of your own payload). In striking contrast, WebSocket uses about 10 bytes, or about 70x less data to talk with the server.
如果您深入研究 HTTP 协议并使用 MVC 框架,您会看到单个 AJAX 请求实际上将 700-900 字节的协议负载仅传输到 AJAX 到 URL(没有您自己的任何负载)。与此形成鲜明对比的是,WebSocket 使用大约 10 个字节或大约 70 倍的数据与服务器通信。
Since SocketIO maintains an open connection, there's no handshake, and server response time is limited to round-trip or ping time to the server itself.
由于 SocketIO 保持开放连接,因此没有握手,并且服务器响应时间仅限于到服务器本身的往返或 ping 时间。
There is misinformation that a socketconnection is a portconnection; it is not. A socket connection is just an entry in a table. Very few resources are consumed, and a single server can provide 1,000,000+ WebSocket connections. An AWS XXL server can and does host 1,000,000+ SocketIO connections.
有错误信息说套接字连接是端口连接;它不是。套接字连接只是表中的一个条目。消耗资源极少,单台服务器可提供1,000,000+ WebSocket连接。AWS XXL 服务器可以并且确实托管 1,000,000 多个 SocketIO 连接。
An AJAX connection will gzip/deflate the entire HTTP headers, decode the headers, encode the headers, and spin up a HTTP server thread to process the request, again, because this is a document protocol; the server was designed to spit out documents a single time.
AJAX 连接将 gzip/deflate 整个 HTTP 标头、解码标头、编码标头,并再次启动 HTTP 服务器线程来处理请求,因为这是一个文档协议;该服务器旨在一次性吐出文档。
In contrast, WebSocket simply stores an entry in a table for a connection, approximately 40-80 bytes. That's literally it. No polling occurs, at all.
相比之下,WebSocket 只是在一个连接表中存储一个条目,大约 40-80 个字节。字面意思就是这样。根本不进行轮询。
WebSocket was designedto scale.
WebSocket旨在扩展。
As far as SocketIO being messy... This is not the case at all. AJAX is messy, you need promise/response.
至于 SocketIO 是凌乱的......根本不是这种情况。AJAX 很乱,你需要承诺/响应。
With SocketIO, you simply have emitters and receivers; they don't even need to know about each-other; no promise system is needed:
使用 SocketIO,您只需拥有发射器和接收器;他们甚至不需要了解彼此;不需要承诺系统:
To request a list of users you simply send the server a message...
要请求用户列表,您只需向服务器发送一条消息...
socket.emit("giveMeTheUsers");
When the server is ready, it will send you back another message. Tada, you're done. So, to process a list of users you simply say what to do when you get a response you're looking for...
当服务器准备好时,它会向您发送另一条消息。田田,你完了。因此,要处理用户列表,您只需在收到要查找的响应时说要做什么...
socket.on("HereAreTheUsers", showUsers(data) );
That's it. Where is the mess? Well, there is none :) Separation of concerns? Done for you. Locking the client so they know they have to wait? They don't have to wait :) You could get a new list of users whenever... The server could even play backany UI command this way... Clients can connect to each otherwithout even using a server with WebRTC...
就是这样。哪里乱了?好吧,没有:) 关注点分离?为你做了。锁定客户端以便他们知道必须等待?他们不必等待 :) 你可以在任何时候获得一个新的用户列表......服务器甚至可以通过这种方式播放任何 UI 命令......客户端甚至可以在不使用带有 WebRTC 的服务器的情况下相互连接...... .
Chat system in SocketIO? 10 lines of code. Real-time video conferencing? 80 lines of codeYes... Luke... Join me. use the right protocol for the job... If you're writing an app... use an app protocol.
SocketIO 中的聊天系统?10行代码。实时视频会议?80 行代码是的...卢克...加入我。为工作使用正确的协议...如果您正在编写应用程序...请使用应用程序协议。
I think the problem and confusion here is coming from people that are used to using AJAX and thinkingthey need all the extra promise protocol on the client and a REST API on the back end... Well you don't. :) It's not needed anymore :)
我认为这里的问题和困惑来自那些习惯于使用 AJAX 并认为他们需要客户端上的所有额外承诺协议和后端的 REST API 的人......好吧,你不需要。:) 不再需要了 :)
yes, you read that right... a REST API is not needed anymore when you decide to switch to WebSocket. REST is actually outdated. if you write a desktop app, do you communicate with the dialog with REST? No :) That's pretty dumb.
是的,您没看错……当您决定切换到 WebSocket 时,不再需要 REST API。REST 实际上已经过时了。如果您编写桌面应用程序,您是否使用 REST 与对话框进行通信?不:) 那太愚蠢了。
SocketIO, utilizing WebSocket does the same thing for you... you can start to think of the client-side as simple the dialog for your app. You no longer need REST, at all.
SocketIO,利用 WebSocket 为您做同样的事情……您可以开始将客户端视为应用程序的简单对话框。您根本不再需要 REST。
In fact, if you try to use REST while using WebSocket, it's just as silly as using REST as the communication protocol for a desktop dialog... there is absolutely no point, at all.
事实上,如果您在使用 WebSocket 的同时尝试使用 REST,这就像使用 REST 作为桌面对话的通信协议一样愚蠢……完全没有意义。
What's that you say Timmy? What about other apps that want to use your app? You should give them access to REST? Timmy... WebSocket has been out for 4 years... Just have them connect to your app using WebSocket, and let them request the messages using thatprotocol... it will consume 50x fewer resources, be much faster, and 10x easier to develop... Why support the past when you're creating the future?
你说蒂米是什么?想要使用您的应用程序的其他应用程序呢?你应该让他们访问 REST 吗?Timmy...WebSocket 已经推出 4 年了...只需让他们使用 WebSocket 连接到您的应用程序,并让他们使用该协议请求消息...它将消耗 50 倍的资源,更快,更容易 10 倍发展……为什么在创造未来时支持过去?
Sure, there are use cases for REST, but they are all for older and outdated systems... Most people just don't know it yet.
当然,REST 有一些用例,但它们都适用于较旧和过时的系统……大多数人只是还不知道。
UPDATE:
更新:
A LOTof people have been asking me recently how can they start writing an app in 2018 (and now soon 2019) using WebSockets, that the barrier seems really high, that once they play with Socket.IO they don't know where else to turn or what to learn.
一个地段的人都在问我最近怎么能开始编写使用的WebSockets在2018年的应用程序(现在快2019),该屏障似乎真的很高,一旦他们与Socket.IO发挥他们不知道还有什么地方转或者学什么。
Fortunately the last 3 years have been very kind to WebSockets...
幸运的是,过去 3 年对 WebSockets 非常友好......
There are now 3 major frameworks that support BOTHREST and WebSocket, and even IoT protocols or other minimal/speedy protocols like ZeroMQ, and you don't have to worry about any of it; you just get support for it out of the box.
现在有3个主要的框架,支持BOTHREST和WebSocket的,甚至物联网的协议或类似ZeroMQ其它最小/快速的协议,你不必任何关于它的担心; 您只需立即获得对它的支持。
Note:Although Meteor is by far the most popular, I am leaving it out because although they are a very, very well-funded WebSocket framework, anyone who has coded with Meteor for a few years will tell you, it's an internal mess and a nightmare to scale. Sort of like WordPress is to PHP, it is there, it is popular, but it is not very well made. It's not well-thought out, and it will soon die. Sorry Meteor folks, but check out these 3 other projects compared to Meteor, and you will throw Meteor away the same day :)
注意:尽管 Meteor 是迄今为止最受欢迎的,但我将其排除在外,因为尽管它们是一个资金非常充足的 WebSocket 框架,但任何使用 Meteor 编码几年的人都会告诉你,这是一个内部混乱和一个规模的噩梦。有点像 WordPress 之于 PHP,它就在那里,它很受欢迎,但它的制作并不是很好。它没有经过深思熟虑,很快就会消亡。抱歉 Meteor 伙计们,但与 Meteor 相比,请查看其他 3 个项目,您会在同一天扔掉 Meteor :)
With all of the below frameworks, you write your service once, and you get both REST and WebSocket support. What's more, it's a single line of config code to swap between almost any backend database.
使用以下所有框架,您只需编写一次服务,即可获得 REST 和 WebSocket 支持。更重要的是,只需一行配置代码即可在几乎所有后端数据库之间进行交换。
FeathersEasiest to use, works the same on the front and backend, and supports most features, Feathers is a collection of light-weight wrappers for existing tools like express. Using awesome tools like feathers-vuex, you can create immutable services that are fully mockable, support REST, WebSocket and other protocols (using Primus), and get free full CRUD operations, including search and pagination, without a single line of code (just some config). Also works really great with generated data like json-schema-fakerso you can not only fully mock things, you can mock it with random yet valid data. You can wire up an app to support type-ahead search, create, delete and edit, with no code(just config). As some of you may know, proper code-through-config is the biggest barrier to self-modifying code. Feathers does it right, and will push you towards the front of the pack in the future of app design.
Feathers最容易使用,在前端和后端工作相同,并支持大多数功能,Feathers 是一个轻量级包装器的集合,用于现有工具,如 express。使用像feathers-vuex这样很棒的工具,您可以创建完全可模拟的不可变服务,支持REST、WebSocket和其他协议(使用Primus),并获得免费的完整CRUD操作,包括搜索和分页,而无需一行代码(只需一些配置)。对于像json-schema-faker这样的生成数据也非常有效,因此您不仅可以完全模拟事物,还可以使用随机但有效的数据模拟它。您可以连接应用程序以支持预先输入搜索、创建、删除和编辑,无需代码(只是配置)。你们中的一些人可能知道,正确的代码直通配置是自我修改代码的最大障碍。Feathers 做对了,它将在未来的应用程序设计中将您推向最前沿。
MoleculerMoleculer is unfortunately an order of magnitude better at the backend than Feathers. While feathers will work, and let you scale to infinity, feathers simply doesn't even begin to think about things like production clustering, live server consoles, fault tolerance, piping logs out of the box, or API Gateways (while I've built a production API gateway out of Feathers, Moleculer does it way, way better). Moleculer is also the fastest growing, both in popularity and new features, than any WebSocket framework.
不幸的是,MoleculerMoleculer 在后端比 Feathers 好一个数量级。虽然feathers 可以工作,并且可以让你无限扩展,但是feathers 根本没有开始考虑诸如生产集群、实时服务器控制台、容错、开箱即用的管道日志或API 网关(虽然我已经构建了Feathers 中的一个生产 API 网关,Moleculer 这样做,方式更好)。Moleculer 也是增长最快的,无论是在流行度还是新功能方面,都比任何 WebSocket 框架都要快。
The winning strike with Moleculer is you can use a Feathers or ActionHero front-end with a Moleculer backend, and although you lose some generators, you gain a lot of production quality.
Moleculer 的制胜法宝是你可以使用 Feathers 或 ActionHero 前端和 Moleculer 后端,虽然你失去了一些生成器,但你获得了很多生产质量。
Because of this I recommend learning Feathers on the front and backend, and once you make your first app, try switching your backend to Moleculer. Moleculer is harder to get started with, but only because it solves all the scaling problems for you, and this information can confuse newer users.
因此,我建议在前端和后端学习 Feathers,一旦您制作了第一个应用程序,请尝试将后端切换到 Moleculer。Moleculer 更难开始使用,但这仅仅是因为它为您解决了所有扩展问题,而这些信息可能会使新用户感到困惑。
ActionHeroListed here as a viable alternative, but Feathers and Moleculer are better implementations. If anything about ActionHero doesn't Jive with you, don't use it; there are two better ways above that give you more, faster.
ActionHero此处列为可行的替代方案,但 Feathers 和 Moleculer 是更好的实现。如果 ActionHero 不适合您,请不要使用它;上面有两种更好的方法可以为您提供更多、更快的方法。
NOTE:API Gateways are the future, and all 3 of the above support them, but Moleculer literally gives you it out of the box. An API gateway lets you massage your client interaction, allowing caching, memoization, client-to-client messaging, blacklisting, registration, fault tolerance and all other scaling issues to be handled by a single platform component. Coupling your API Gateway with Kubernetes will let you scale to infinity with the least amount of problems possible. It is the best design method available for scalable apps.
注意:API 网关是未来,并且上述所有 3 种网关都支持它们,但 Moleculer 确实为您提供了开箱即用的功能。API 网关可让您处理客户端交互,允许缓存、记忆、客户端到客户端消息传递、黑名单、注册、容错和所有其他扩展问题由单个平台组件处理。将您的 API 网关与 Kubernetes 相结合,可以让您以尽可能少的问题扩展到无限。这是可用于可扩展应用程序的最佳设计方法。
回答by Reza Hashemi
Socket.IO uses persistent connection between client and server, so you will reach a maximum limit of concurrent connections depending on the resources you have on server side, while more Ajax async requests can be served with the same resources.
Socket.IO 使用客户端和服务器之间的持久连接,因此您将根据服务器端的资源达到并发连接的最大限制,而相同的资源可以处理更多的 Ajax 异步请求。
Socket.IO is mainly designed for realtime and bi-directional connections between client and server and in some applications there is no need to keep permanent connections. On the other hand Ajax async connections should pass the HTTP connection setup phase and send header data and all cookies with every request.
Socket.IO 主要是为客户端和服务器之间的实时和双向连接而设计的,在某些应用程序中不需要保持永久连接。另一方面,Ajax 异步连接应该通过 HTTP 连接设置阶段,并随每个请求发送标头数据和所有 cookie。
Socket.IO has been designed as a single process server and may have scalability issues depending server resources that you are bound to.
Socket.IO 被设计为单进程服务器,根据您绑定到的服务器资源,可能存在可扩展性问题。
Socket.IO in not well suited for applications when you are better to cache results of client requests.
当您更好地缓存客户端请求的结果时,Socket.IO 不太适合应用程序。
Socket.IO applications face with difficulties with SEO optimization and search engine indexing.
Socket.IO 应用程序在 SEO 优化和搜索引擎索引方面面临困难。
Socket.IO is not a standard and not equivalent to W3C Web Socket API, It uses current Web Socket API if browser supports, socket.io created by a person to resolve cross browser compatibility in real time apps and is so young, about 1 year old. Its learning curve, less developers and community resources compared with ajax/jquery, long term maintenance and less need or better options in future may be important for developer teams to make their code based on socket.io or not.
Socket.IO 不是标准,不等同于 W3C Web Socket API,如果浏览器支持,它使用当前的 Web Socket API,socket.io 是一个人为解决实时应用程序的跨浏览器兼容性而创建的,还很年轻,大约 1 年老的。它的学习曲线、与 ajax/jquery 相比更少的开发人员和社区资源、长期维护和更少的需求或未来更好的选择对于开发人员团队是否基于 socket.io 制作他们的代码可能很重要。