Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using socket.io as api

I am surprised that I can't find any questions on this. How do you implement REST over WebSockets uniformly? I am building a web app and would like to use websockets over ajax calls.

First, how do you represent a URI? Second, how do you represent the HTTP methods (GET, PUT, POST, …)?

socket.emit('set', ...)
socket.emit('get', ...)
socket.emit('delete', ...)
like image 901
sdfadfaasd Avatar asked Jan 03 '12 03:01

sdfadfaasd


2 Answers

This makes no sense. The whole point of using WebSockets is bypassing the overhead imposed by doing HTTP requests. You want to re-implement HTTP on top of streaming HTTP.

In most cases it will actually cause more overhead, because if the client does not support WebSockets or Flash sockets, it will fall back to HTTP long-polling. Which means you have a fake HTTP request and the actual HTTP request delivering the data.

If you want to build a RESTful app, use HTTP.

If you want to build an event-driven app, use WebSockets.

Use the right tool for the job.

like image 184
igorw Avatar answered Sep 23 '22 22:09

igorw


This link probably describes what you are trying to do:

How can Socket.io and RESTFul work together?

It's not wrong to want to have messages such as GET, SET, DELETE. It's not wrong to reuse your existing API structure- you still need routing and the URI can be parsed by your routing on the server side to correspond to a controller for GET / SET / DELETE.

e.g.:

socket.emit('set', {uri: 'https://stackoverflow.com/questions/6339393/how-can-socket-io-and-restful-work-together', params: {someKey: "someValue}).

This doesn't capitalize on what websockets does well - bi-directional communication, but it does allow for streaming requests, which probably will be faster depending on how often you poll your data.

like image 38
nym Avatar answered Sep 21 '22 22:09

nym