Using socket.io as an api

I am surprised that I can not find any questions about this. How do you implement REST over WebSockets evenly? I am building a web application and would like to use websockets for ajax calls.

First, how do you represent a URI? Secondly, how do you imagine the HTTP methods (GET, PUT, POST, ...)?

socket.emit('set', ...) socket.emit('get', ...) socket.emit('delete', ...) 
+6
source share
2 answers

This link probably describes what you are trying to do:

How do Socket.io and RESTFul work together?

It is wrong to want to have messages like GET, SET, DELETE. Repeating the use of the existing API structure is wrong - you still need routing and the URI can be parsed by your server side routing to match the controller for GET / SET / DELETE.

eg:.

 socket.emit('set', {uri: '/questions/199060/how-can-socketio-and-restful-work-together', params: {someKey: "someValue}). 

This does not use what websockets does well - bidirectional communication, but it does allow streaming requests, which are likely to be faster depending on how often you poll your data.

Good luck and stay frosty!

+10
source

It does not make sense. The whole point of using WebSockets is to bypass the overhead caused by executing HTTP requests. You want to reimplement HTTP over HTTP streaming.

In most cases, this will actually cause additional overhead, because if the client does not support WebSockets or flash sockets, it will return to a lengthy HTTP poll. This means that you have a fake HTTP request and the actual HTTP request sending the data.

If you want to create a RESTful application, use HTTP.

If you want to create an event-driven application, use WebSockets.

Use the right tool for the job.

+9
source

Source: https://habr.com/ru/post/904955/


All Articles