我已经使用WebSockets有一段时间了,我选择在大学最后一年的项目中使用Node服务器和WebSockets创建一个敏捷项目管理工具。我发现使用WebSockets使我的应用程序每秒可以处理的请求数量增加了624%。

然而,自从开始项目,我读到安全漏洞,和一些浏览器选择禁用WebSockets默认。

这让我想到一个问题:

既然WebSockets在降低延迟和资源开销方面做得如此出色,为什么还要使用AJAX呢? AJAX在哪些方面比WebSockets做得更好呢?


当前回答

WebSockets不能在旧的浏览器中工作,而那些支持它的浏览器通常有不同的实现。这也是为什么它们没有一直被用来代替AJAX的唯一原因。

其他回答

WebSockets不能在旧的浏览器中工作,而那些支持它的浏览器通常有不同的实现。这也是为什么它们没有一直被用来代替AJAX的唯一原因。

除了老式浏览器的问题(包括IE9,因为WebSockets将从IE10开始支持),网络中介还不支持WebSockets,包括透明代理、反向代理和负载平衡器,仍然存在很大的问题。 有一些移动运营商完全阻断WebSocket流量(即在HTTP UPGRADE命令之后)。

随着时间的推移,WebSockets将得到越来越多的支持,但与此同时,您应该始终有一个基于http的回退方法来将数据发送到浏览器。

HTTP和Websockets之间的区别的一个例子,它是一个客户端大小的库,可以处理Websocket端点(如REST api)和客户端上的Websockets端点(如Websockets)。 https://github.com/mikedeshazer/sockrest 此外,对于那些试图在客户端使用websocket API的人,或者相反,他们习惯的方式。libs/sockrest.js很清楚地说明了这些区别(或者应该是这样)。

我不认为我们可以对Websockets和HTTP做一个清晰的比较,因为它们不是竞争对手,也解决不了同样的问题。

Websockets是一个很好的选择,可以以接近实时的方式处理长时间的双向数据流,而REST则适合偶尔的通信。使用websockets是一项相当大的投资,因此它对于偶尔的连接来说是一种过度的使用。

你可能会发现Websockets在高负载时做得更好,HTTP在某些情况下稍微快一点,因为它可以利用缓存。比较REST和Websockets就像比较苹果和橘子。

我们应该检查哪个为我们的应用程序提供了更好的解决方案,哪个最适合我们的用例胜出。

WebSockets并不打算取代AJAX,甚至严格来说也不是Comet/long-poll的替代品(尽管在许多情况下这是有意义的)。

WebSockets的目的是在浏览器和服务器之间提供低延迟、双向、全双工和长时间运行的连接。WebSockets为浏览器应用程序打开了新的应用领域,这是使用HTTP和AJAX无法实现的(交互式游戏、动态媒体流、到现有网络协议的桥接等)。

However, there is certainly an overlap in purpose between WebSockets and AJAX/Comet. For example, when the browser wants to be notified of server events (i.e. push) then Comet techniques and WebSockets are certainly both viable options. If your application needs low-latency push events then this would be a factor in favor of WebSockets. On the other hand, if you need to co-exist with existing frameworks and deployed technologies (OAuth, RESTful APIs, proxies, load balancers) then this would be a factor in favor of Comet techniques (for now).

如果你不需要WebSockets提供的特定好处,那么坚持使用现有的技术,如AJAX和Comet,可能是一个更好的主意,因为这允许你重用和集成一个巨大的现有生态系统的工具,技术,安全机制,知识库(例如,stackoverflow上了解HTTP/ AJAX /Comet的人比WebSockets多得多),等等。

另一方面,如果您正在创建的新应用程序不能在HTTP/Ajax/Comet的延迟和连接限制内很好地工作,那么可以考虑使用WebSockets。

Also, some answers indicate that one of the downsides of WebSockets is limited/mixed server and browser support. Let me just diffuse that a bit. While iOS (iPhone, iPad) still supports the older protocol (Hixie) most WebSockets servers support both Hixie and the HyBi/IETF 6455 version. Most other platforms (if they don't already have built-in support) can get WebSockets support via web-socket-js (Flash based polyfill). This covers the vast majority of web users. Also, if you are using Node for the server backend, then consider using Socket.IO which includes web-socket-js as a fallback and if even that is not available (or disabled) then it will fall back to using whatever Comet technique is available for the given browser.

更新:iOS 6现在支持当前的HyBi/IETF 6455标准。