Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using WebSockets... Efficiently?

I've read pretty much every guide and tutorial I can find on WebSockets, but not one of them has covered how to use them efficiently.

Does anyone have any sort of guide on how to do this? I'm concerned about the amount of bandwidth a single connection can take up, especially when applications have hundrends of connections opened.

like image 434
Alexander Avatar asked Jun 01 '11 19:06

Alexander


1 Answers

The efficiency in WebSocket depends on the implementation and architecture of the webserver that handles them. WebSocket is a very efficient protocol with only 2 byte (!) overhead, compare to the all different HTTP header fields and HTTP cookies that is sent in every Ajax request.

Usually an efficient webserver for websockets should be event driven (see the examples below). In opposite, the traditional way to implement web servers have been to spawn a new thread per request. But threads allocate much memory e.g. 256MB per thread. So if you have 1GB memory on your server you can't handle very many requests concurrently. But if your server is event-driven your memory usage will be almost constant, since new threads aren't created. See also Technically why is processes in Erlang more efficient than OS threads?

You can send any data in your WebSockets. JSON is efficient if the client is a web browser, or maybe typed arrays. If your client is a custom application, you can use Protocol Buffers. See also Google Wave Client-Server Protocol Whitepaper

You can implement efficient websocket servers using Twisted (Python) or Netty (Java). Play Framework is an efficient web framework for Java and Scala implemented on Netty. Another efficient alternative is Yaws web server (Erlang) or Node.js + Socket.io (JavaScript).

As an application developer, the less data you send the more efficient (less traffic) and the less load on your server.

like image 186
Jonas Avatar answered Oct 11 '22 10:10

Jonas