Javascript Websocket API 取代 REST API?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6806263/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:16:34  来源:igfitidea点击:

Websocket API to replace REST API?

javascriptrestnode.jswebsocket

提问by Harry

I have an application whose primary function works in real time, through websockets or long polling.

我有一个应用程序,其主要功能通过 websockets 或长轮询实时工作。

However, most of the site is written in a RESTful fashion, which is nice for application s and other clients in the future. However, I'm thinking about transitioning to a websocket API for all site functions, away from REST. That would make it easier for me to integrate real time features into all parts of the site. Would this make it more difficult to build applications or mobile clients?

但是,该站点的大部分内容都是以 RESTful 方式编写的,这对于未来的应用程序和其他客户端来说非常有用。但是,我正在考虑从 REST 过渡到所有站点功能的 websocket API。这将使我更容易将实时功能集成到网站的所有部分。这会使构建应用程序或移动客户端变得更加困难吗?

I found that some people are already doing stuff like this: SocketStream

我发现有些人已经在做这样的事情:SocketStream

采纳答案by Tauren

Not to say that the other answers here don't have merit, they make some good points. But I'm going to go against the general consensus and agree with you that moving to websockets for more than just realtime features is very appealing.

并不是说这里的其他答案没有优点,它们提出了一些很好的观点。但我将与普遍共识背道而驰,并同意你的观点,即转向 websockets 不仅仅是为了实时功能是非常有吸引力的。

I am seriously considering moving my app from a RESTful architecture to more of an RPC style via websockets. This is not a "toy app", and I'm not talking about only realtime features, so I do have reservations. But I see many benefits in going this route and feel it could turn out to be an exceptional solution.

我正在认真考虑通过 websockets 将我的应用程序从 RESTful 架构转移到更多的 RPC 风格。这不是一个“玩具应用程序”,我不只是在谈论实时功能,所以我有保留。但我看到走这条路的很多好处,并觉得它可能会成为一个特殊的解决方案。

My plan is to use DNode, SocketIO, and Backbone. With these tools, my Backbone models and collections can be passed around from/to client and server by simply calling a functions RPC-style. No more managing REST endpoints, serializing/deserializing objects, and so forth. I haven't worked with socketstream yet, but it looks worth checking out.

我的计划是使用DNodeSocketIOBackbone。使用这些工具,我的 Backbone 模型和集合可以通过简单地调用 RPC 样式的函数从/向客户端和服务器传递。不再需要管理 REST 端点、序列化/反序列化对象等。我还没有使用过 socketstream,但看起来值得一试。

I still have a long way to go before I can definitively say this is a good solution, and I'm sure it isn't the best solution for every application, but I'm convinced that this combination would be exceptionally powerful. I admit that there are some drawbacks, such as losing the ability to cache resources. But I have a feeling the advantages will outweigh them.

在我明确地说这是一个很好的解决方案之前,我还有很长的路要走,而且我确信它不是适用于每个应用程序的最佳解决方案,但我相信这种组合会非常强大。我承认有一些缺点,比如失去缓存资源的能力。但我有一种感觉,优势会超过它们。

I'd be interested in following your progress exploring this type of solution. If you have any github experiments, please point me at them. I don't have any yet, but hope to soon.

我有兴趣跟踪您探索此类解决方案的进度。如果你有任何 github 实验,请指点我。我还没有,但希望很快。

Below is a list of to-read-later links that I've been collecting. I can't vouch that they are all worthwhile, as I've only skimmed many of them. But hopefully some will help.

下面是我一直在收集的稍后阅读链接的列表。我不能保证它们都是值得的,因为我只是略读了其中的许多。但希望有些人会有所帮助。



Great tutorial on using Socket.IO with Express. It exposes express sessions to socket.io and discusses how to have different rooms for each authenticated user.

关于在 Express 中使用 Socket.IO 的很棒的教程。它向 socket.io 公开了 express 会话,并讨论了如何为每个经过身份验证的用户提供不同的房间。

Tutorial on node.js/socket.io/backbone.js/express/connect/jade/redis with authentication, Joyent hosting, etc:

node.js/socket.io/backbone.js/express/connect/jade/redis 教程,带身份验证、Joyent 托管等:

Tutorial on using Pusher with Backbone.js (using Rails):

关于在 Backbone.js 中使用 Pusher 的教程(使用 Rails):

Build application with backbone.js on the client and node.js with express, socket.io, dnode on the server.

在客户端使用backbone.js 构建应用程序,在服务器上使用express、socket.io、dnode 构建node.js。

Using Backbone with DNode:

在 DNode 中使用 Backbone:

回答by Jonas

HTTP REST and WebSockets are very different. HTTP is stateless, so the web server doesn't need to know anything, and you get caching in the web browser and in proxies. If you use WebSockets, your server is becoming statefuland you need to have a connection to the client on the server.

HTTP REST 和 WebSockets 非常不同。HTTP 是无状态的,因此 Web 服务器不需要知道任何信息,并且您可以在 Web 浏览器和代理中缓存。如果您使用 WebSockets,您的服务器将变为有状态,您需要连接到服务器上的客户端。

Request-Reply communication vs Push

请求-回复通信与推送

Use WebSockets only if you need to PUSHdata from the server to the client, that communication pattern is not included in HTTP (only by workarounds). PUSH is helpful if events created by other clients needs to be available to other connected clients e.g. in games where users should act on other clients behaviour. Or if your website is monitoring something, where the server pushes data to the client all the time e.g. stock markets (live).

仅当您需要将数据从服务器送到客户端时才使用 WebSocket ,该通信模式不包含在 HTTP 中(仅通过变通方法)。如果其他客户端创建的事件需要对其他连接的客户端可用,例如在用户应该对其他客户端行为采取行动的游戏中,PUSH 会很有帮助。或者,如果您的网站正在监控某些内容,服务器会一直向客户端推送数据,例如股票市场(实时)。

If you don't need to PUSH data from the server, it's usually easier to use a stateless HTTP REST server. HTTP uses a simple Request-Replycommunication pattern.

如果您不需要从服务器推送数据,使用无状态 HTTP REST 服务器通常更容易。HTTP 使用简单的请求-回复通信模式。

回答by Ravindra babu

I'm thinking about transitioning to a WebSocket api for all site functions

我正在考虑为所有站点功能过渡到 WebSocket api

No. You should not do it. There is no harm if you support both models. Use RESTfor one way communication/simple requests & WebSocketfor two way communication especially when server want to send real time notification.

不,你不应该这样做。如果您同时支持这两种模型,就没有什么坏处。使用REST进行单向通信/简单请求,使用WebSocket进行双向通信,尤其是当服务器想要发送实时通知时。

WebSocketis a more efficient protocol than RESTful HTTPbut still RESTful HTTPscores over WebSocket in below areas.

的WebSocket比更有效的协议的RESTful HTTP但仍RESTful的HTTP分数超过WebSocket的下面的区域。

  1. Create/Update/Delete resources have been defined well for HTTP. You have to implement these operations at low level for WebSockets.

  2. WebSocket connections scale vertically on a single server where as HTTP connections scale horizontally. There are some proprietary non standards-based solutions for WebSocket horizontal scaling .

  3. HTTP comes with a lot of good features such as caching, routing, multiplexing, gzipping etc. These have to built on top of Websocket if you chose Websocket.

  4. Search engine optimizations works well for HTTP URLs.

  5. All Proxy, DNS, firewalls are not yet fully aware of WebSocket traffic. They allow port 80 but might restrict traffic by snooping on it first.

  6. Security with WebSocket is all-or-nothing approach.

  1. 创建/更新/删除资源已经为 HTTP 定义好了。您必须在低级别为 WebSockets 实现这些操作。

  2. WebSocket 连接在单个服务器上垂直扩展,而 HTTP 连接水平扩展。有一些专有的非基于标准的 WebSocket 水平缩放解决方案。

  3. HTTP 有很多很好的特性,比如缓存、路由、多路复用、gzip 压缩等。如果你选择 Websocket,这些都必须建立在 Websocket 之上。

  4. 搜索引擎优化适用于 HTTP URL。

  5. 所有代理、DNS、防火墙尚未完全了解 WebSocket 流量。它们允许端口 80,但可能会通过先窥探它来限制流量。

  6. WebSocket 的安全性是一种全有或全无的方法。

Have a look at this articlefor more details.

看看这篇文章了解更多详情。

回答by Raynos

The only problem I can using TCP (WebSockets) as your main web content delivery strategy is that there is very little reading material out there about how to design your website architecture and infrastructure using TCP.

我可以使用 TCP (WebSockets) 作为您的主要 Web 内容交付策略的唯一问题是关于如何使用 TCP 设计您的网站架构和基础设施的阅读材料很少。

So you can't learn from other people's mistakes and development is going to be slower. It's also not a "tried and tested" strategy.

所以你不能从别人的错误中吸取教训,发展会更慢。这也不是“久经考验”的策略。

Of course your also going to lose all the advantages of HTTP (Being stateless, and caching are the bigger advantages).

当然,您也将失去 HTTP 的所有优势(无状态和缓存是更大的优势)。

Remember that HTTP is an abstraction for TCP designed for serving web content.

请记住,HTTP 是 TCP 的抽象,旨在为 Web 内容提供服务。

And let's not forget that SEO and search engines don't do websockets. So you can forget about SEO.

我们不要忘记 SEO 和搜索引擎不做 websockets。所以你可以忘记SEO。

Personally I would recommend against this as there's too much risk.

我个人建议不要这样做,因为风险太大。

Don't use WS for serving websites, use it for serving web applications

不要将 WS 用于服务网站,而是将其用于服务 Web 应用程序

However if you have a toy or a personal websites by all means go for it. Try it, be cutting-edge.For a business or company you cannot justify the risk of doing this.

但是,如果您有玩具或个人网站,务必尝试尝试一下,成为最前沿的。对于企业或公司,您无法证明这样做的风险是合理的。

回答by bvdb

I learned a little lesson (the hard way). I made a number crunching application that runs on Ubuntu AWS EC2 cloud services (uses powerful GPUs), and I wanted to make a front-end for it just to watch its progress in realtime. Due to the fact that it needed realtime data, it was obvious that I needed websockets to push the updates.

我学到了一点教训(艰难的方式)。我制作了一个在 Ubuntu AWS EC2 云服务(使用强大的 GPU)上运行的数字运算应用程序,我想为它制作一个前端,只是为了实时观察它的进展。由于它需要实时数据,很明显我需要 websockets 来推送更新。

It started with a proof of concept, and worked great. But then when we wanted to make it available to the public, we had to add user session, so we needed login features. And no matter how you look at it, the websocket has to know which user it deals with, so we took the shortcut of using the websockets to authenticate the users. It seemed obvious, and it was convenient.

它从概念验证开始,效果很好。但是当我们想让它对公众可用时,我们不得不添加用户会话,所以我们需要登录功能。而且不管你怎么看,websocket 都必须知道它处理的是哪个用户,所以我们采取了使用 websockets 来验证用户的捷径。这看起来很明显,而且很方便。

We actually had to spend quiet some time to make the connections reliable. We started out with some cheap websocket tutorials, but discovered that our implementation was not able to automatically reconnect when the connection was broken. That all improved when we switched to socket-io. Socket-io is a must !

我们实际上不得不安静一些时间以使连接可​​靠。我们从一些廉价的 websocket 教程开始,但发现我们的实现无法在连接中断时自动重新连接。当我们切换到 socket-io 时,这一切都得到了改善。Socket-io 是必须的!

Having said all that, to be honest, I think we missed out on some great socket-io features.Socket-io has a lot more to offer, and I am sure, if you take it in account in your initial design, you can get more out of it. In contrast, we just replaced the old websockets with the websocket functionality of socket-io, and that was it. (no rooms, no channels, ...) A redesign could have made everything more powerful. But we didn't have time for that. That's something to remember for our next project.

说了这么多,老实说,我认为我们错过了一些很棒的 socket-io 功能。Socket-io 可以提供更多功能,我相信,如果您在最初的设计中考虑到它,您可以从中获得更多。相比之下,我们只是用 socket-io 的 websocket 功能替换了旧的 websocket,仅此而已。(没有房间,没有频道,......)重新设计本可以让一切变得更强大。但我们没有时间这样做。这是我们下一个项目要记住的事情。

Next we started to storemore and more data (user history, invoices, transactions, ...). We stored all of it in an AWS dynamodb database, and AGAIN, we used socket-io to communicate the CRUD operations from the front-end to the backend. I think we took a wrong turn there. It was a mistake.

接下来我们开始存储越来越多的数据(用户历史、发票、交易……)。我们将所有这些都存储在 AWS dynamodb 数据库中,再次使用 socket-io 将 CRUD 操作从前端传递到后端。我想我们在那里拐错了弯。那是一个错误。

  • Because shortly after we found out that Amazon's cloud services (AWS) offer some great load-balancing/scaling tools for RESTful applications.
  • We have the impression now that we need to write a lot of code to perform the handshakesof the CRUD operations.
  • Recently we implemented Paypal integration. We managed to get it to work. But again, all tutorials are doing it with RESTful APIs. We had to rewrite/rethink their examples to implement them with websockets. We got it to work fairly fast though. But it does feel like we are going against the flow.
  • 因为在我们发现 Amazon 的云服务 (AWS)为 RESTful 应用程序提供了一些出色的负载平衡/扩展工具后不久。
  • 我们现在的印象是,我们需要编写大量代码来执行CRUD 操作的握手
  • 最近我们实现了 Paypal 集成。我们设法让它发挥作用。但同样,所有教程都是使用 RESTful API 来完成的。我们不得不重写/重新思考他们的例子,用 websockets 来实现它们。不过,我们让它运行得相当快。但确实感觉我们在逆流而上。

Having said all that, we are going live next week. We got there in time, everything works. And it's fast, but will it scale ?

说了这么多,我们下周就要直播了。我们及时到达那里,一切正常。它很快,但它会扩展吗?

回答by Archimedes Trajano

I would consider using both. Each technology has their merit and there is no one-size fits all solution.

我会考虑同时使用两者。每种技术都有其优点,没有一刀切的解决方案。

The separation of work goes this way:

工作的分离是这样的:

  1. WebSocketswould be the primary methodof an application to communicate with the server where a session is required. This eliminates many hacks that are needed for the older browsers (the problem is support for the older browsers which will eliminate this)

  2. RESTful APIis used for GET calls that are not session oriented(i.e. not authentication needed) that benefit from browser caching. A good example of this would be reference data for drop downs used by a web application. However. can change a bit more often than...

  3. HTML and Javascript. These comprise the UI of the webapp. These would generally benefit being placed on a CDN.

  4. Web Services using WSDLare still the best way of enterprise leveland cross-enterprise communication as it provides a well defined standard for message and data passing. Primarily you'd offload this to a Datapower device to proxy to your web service handler.

  1. WebSockets将是应用程序与需要会话的服务器进行通信的主要方法。这消除了旧浏览器所需的许多黑客攻击(问题是对旧浏览器的支持将消除这一点)

  2. RESTful API用于非面向会话(即不需要身份验证)的GET 调用,这些调用受益于浏览器缓存。一个很好的例子是 Web 应用程序使用的下拉菜单的参考数据。然而。可以比……更频繁地改变

  3. HTML 和 JavaScript。这些构成了 webapp 的 UI。这些通常会有益于放置在 CDN 上。

  4. 使用WSDL 的Web 服务仍然是企业级和跨企业通信的最佳方式,因为它为消息和数据传递提供了定义明确的标准。主要是您将其卸载到 Datapower 设备以代理到您的 Web 服务处理程序。

All of this happen on the HTTP protocol which gives use secure sockets via SSL already.

所有这些都发生在 HTTP 协议上,该协议已经通过 SSL 提供了安全套接字。

For the mobile application though, websockets cannot reconnect back to a disconnected session (How to reconnect to websocket after close connection) and managing that isn't trivial. So for mobile apps, I would still recommend REST APIand polling.

但是,对于移动应用程序,websockets 无法重新连接回断开连接的会话(如何在关闭连接后重新连接到 websocket)并且管理这不是微不足道的。因此,对于移动应用程序,我仍然会推荐 REST API和轮询。

Another thing to watch out for when using WebSockets vs REST is scalability. WebSocket sessions are still managed by the server. RESTful API when done properly are stateless (which mean there is no server state that needs to be managed), thus scalability can grow horizontally (which is cheaper) than vertically.

使用 WebSockets 与 REST 时要注意的另一件事是可扩展性。WebSocket 会话仍然由服务器管理。RESTful API 在正确完成时是无状态的(这意味着没有需要管理的服务器状态),因此可扩展性可以水平增长(比垂直增长更便宜)

回答by Michael Cole

Do I want updates from the server?

我想要来自服务器的更新吗?

  • Yes: Socket.io
  • No: REST
  • 是:Socket.io
  • 没有休息

The downsides to Socket.io are:

Socket.io 的缺点是:

  • Scalability: WebSockets require open connections and a much different Ops setup to web scale.
  • Learnin: I don't have unlimited time for my learnin. Things have to get done!
  • 可扩展性:WebSockets 需要开放连接和非常不同的操作设置才能进行网络扩展。
  • 学习:我没有无限的学习时间。事情必须完成!

I'll still use Socket.io in my project, but not for basic web forms that REST will do nicely.

我仍然会在我的项目中使用 Socket.io,但不会用于 REST 可以很好地处理的基本 Web 表单。

回答by yojimbo87

WebSockets (or long polling) based transports mostly serve for (near) real-time communication between the server and client. Although there are numerous scenarios where these kinds of transports are required, such as chat or some kind of real-time feeds or other stuff, not all parts of some web application need to be necessarily connected bidirectionally with the server.

基于 WebSockets(或长轮询)的传输主要用于服务器和客户端之间的(近)实时通信。尽管有许多场景需要这些类型的传输,例如聊天或某种实时提要或其他东西,但并非某些 Web 应用程序的所有部分都需要与服务器双向连接。

REST is resource based architecture which is well understood and offers it's own benefits over other architectures. WebSockets incline more to streams/feeds of data in real-time which would require you to create some kind of server based logic in order to prioritize or differentiate between resources and feeds (in case you don't want to use REST).

REST 是基于资源的架构,它被很好地理解并提供了优于其他架构的自身优势。WebSockets 更倾向于实时数据流/馈送,这需要您创建某种基于服务器的逻辑,以便对资源和馈送进行优先级排序或区分(以防您不想使用 REST)。

I assume that eventually there would be more WebSockets centric frameworks like socketstreamin the future when this transport would be more widespread and better understood/documented in the form of data type/form agnostic delivery. However, I think, this doesn't mean that it would/should replace the REST just because it offers functionality which isn't necessarily required in numerous use cases and scenarios.

我认为将来最终会出现更多以 WebSockets 为中心的框架,如socketstream,届时这种传输将更广泛,并且以数据类型/形式不可知交付的形式更好地理解/记录。但是,我认为,这并不意味着它会/应该仅仅因为 REST 提供了许多用例和场景中不一定需要的功能而替换它。

回答by zeekay

That's not a good idea. The standard isn't even finalized yet, support varies across browsers, etc. If you want to do this now you'll end up needing to fallback to flash or long polling, etc. In the future it probably still won't make a lot of sense, since the server has to support leaving connections open to every single user. Most web servers are designed instead to excel at quickly responding to requests and closing them as quickly as possibly. Heck even your operating system would have to be tuned to deal with a high number of simultaneous connections (each connection using up more ephemeral ports and memory). Stick to using REST for as much of the site as you can.

这不是一个好主意。该标准甚至还没有最终确定,支持因浏览器而异,等等。如果你现在想这样做,你最终需要回退到 Flash 或长轮询等。将来它可能仍然不会成为一个很有意义,因为服务器必须支持对每个用户开放连接。大多数 Web 服务器被设计为擅长快速响应请求并尽可能快地关闭它们。哎呀,甚至您的操作系统也必须进行调整以处理大量同时连接(每个连接使用更多的临时端口和内存)。坚持尽可能多地在网站上使用 REST。