Programing

REST API를 대체하는 Websocket API?

lottogame 2020. 8. 26. 08:21
반응형

REST API를 대체하는 Websocket API?


웹 소켓 또는 긴 폴링을 통해 기본 기능이 실시간으로 작동하는 응용 프로그램이 있습니다.

그러나 대부분의 사이트는 RESTful 방식으로 작성되어 향후 애플리케이션 및 기타 클라이언트에 유용합니다. 그러나 REST에서 벗어난 모든 사이트 기능에 대해 웹 소켓 API로 전환하는 것을 생각하고 있습니다. 그러면 사이트의 모든 부분에 실시간 기능을 더 쉽게 통합 할 수 있습니다. 이것이 애플리케이션이나 모바일 클라이언트를 구축하는 것을 더 어렵게 만들까요?

나는 어떤 사람들이 이미 다음과 같은 일을하고 있음을 발견했다 : SocketStream


여기에있는 다른 답변에는 장점이 없다는 말이 아니라 좋은 점이 있습니다. 그러나 저는 일반적인 합의에 어긋나고 실시간 기능 이상을 위해 웹 소켓으로 이동하는 것이 매우 매력적이라는 데 동의합니다.

내 앱을 RESTful 아키텍처에서 웹 소켓을 통해 더 많은 RPC 스타일로 옮기는 것을 진지하게 고려하고 있습니다. 이것은 "장난감 앱"이 아니고 실시간 기능 만 말하는 것이 아니므로 예약을하고 있습니다. 그러나 나는이 길을 가면서 많은 이점을보고 그것이 탁월한 해결책이 될 수 있다고 생각합니다.

내 계획은 DNode , SocketIOBackbone을 사용하는 것 입니다. 이러한 도구를 사용하면 단순히 RPC 스타일의 함수를 호출하여 클라이언트와 서버에서 내 백본 모델과 컬렉션을 전달할 수 있습니다. 더 이상 REST 끝점 관리, 개체 직렬화 / 역 직렬화 등을 수행 할 필요가 없습니다. 아직 socketstream으로 작업하지 않았지만 확인해 볼 가치가 있습니다.

이것이 좋은 솔루션이라고 확실히 말하기까지는 아직 갈 길이 멀고, 모든 애플리케이션에 가장 적합한 솔루션은 아니지만이 조합이 매우 강력 할 것이라고 확신합니다. 리소스 캐시 기능을 잃는 것과 같은 몇 가지 단점이 있음을 인정합니다. 그러나 나는 장점이 그들보다 클 것이라고 생각합니다.

이러한 유형의 솔루션을 탐색하는 진행 상황을 추적하고 싶습니다. github 실험이 있으시면 저에게 알려주세요. 아직은 없지만 곧있을 수 있기를 바랍니다.

아래는 내가 수집 한 나중에 읽을 링크 목록입니다. 나는 그것들 중 많은 것을 훑어 보았 기 때문에 그것들이 모두 가치가 있다는 것을 보증 할 수 없습니다. 그러나 일부는 도움이 될 것입니다.


Express와 함께 Socket.IO 사용에 대한 훌륭한 자습서. 그것은 socket.io에 익스프레스 세션을 노출하고 인증 된 각 사용자에 대해 다른 방을 갖는 방법에 대해 설명합니다.

인증, Joyent 호스팅 등을 사용하는 node.js / socket.io / backbone.js / express / connect / jade / redis에 대한 자습서 :

Backbone.js와 함께 Pusher를 사용하는 방법에 대한 자습서 (Rails 사용) :

클라이언트에서 backbone.js를 사용하고 서버에서 express, socket.io, dnode를 사용하여 node.js로 애플리케이션을 빌드하십시오.

DNode와 함께 백본 사용 :


HTTP REST와 WebSocket은 매우 다릅니다. HTTP는 상태 비 저장 이므로 웹 서버는 아무것도 알 필요가 없으며 웹 브라우저와 프록시에서 캐싱됩니다. WebSocket을 사용하는 경우 서버가 상태 저장 이되고 서버 의 클라이언트에 연결해야합니다.

요청-응답 통신과 푸시

WebSockets 는 서버에서 클라이언트로 데이터 PUSH 해야하는 경우에만 사용 합니다. 해당 통신 패턴은 HTTP에 포함되지 않습니다 (해결 방법에 의해서만). PUSH는 다른 클라이언트가 만든 이벤트를 다른 연결된 클라이언트에서 사용할 수 있어야하는 경우에 유용합니다 (예 : 사용자가 다른 클라이언트 동작에 따라 행동해야하는 게임). 또는 웹 사이트가 무언가를 모니터링하는 경우 서버가 항상 데이터를 클라이언트에 푸시합니다 (예 : 주식 시장 (라이브)).

서버에서 데이터를 PUSH 할 필요가없는 경우 일반적으로 상태 비 저장 HTTP REST 서버를 사용하는 것이 더 쉽습니다. HTTP는 간단한 요청-응답 통신 패턴을 사용합니다.


모든 사이트 기능에 대해 WebSocket API로 전환하는 것에 대해 생각하고 있습니다.

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

WebSocket is a more efficient protocol than RESTful HTTP but still RESTful HTTP scores over WebSocket in below areas.

  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.

Have a look at this article for more details.


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.

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).

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

And let's not forget that SEO and search engines don't do websockets. So you can forget about 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

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.


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. WebSockets would be the primary method of 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 API is 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 WSDL are still the best way of enterprise level and 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.

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

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 API and polling.

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.


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.

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.

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 !

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.

Next we started to store more 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.

  • 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 handshakes of 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.

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 ?


Do I want updates from the server?

  • Yes: Socket.io
  • No: REST

The downsides to Socket.io are:

  • 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!

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


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.

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).

I assume that eventually there would be more WebSockets centric frameworks like socketstream in 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.


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.

참고URL : https://stackoverflow.com/questions/6806263/websocket-api-to-replace-rest-api

반응형