DEV Community

Chan Ho Ahn
Chan Ho Ahn

Posted on

WebSocket vs. Long polling HTTP

WebSocket is a standard protocol for two-way data transfer between a client and a server. The webSocket protocol is built on TCP, not running on over HTTP protocol. Using HTTP polling is hugely disadvantageous as it wastes resource and may cause connection time out.

I recently worked on Chatapp using AJAX for storing chat history to DB on the server side. The server side also runs Socket.io. As AJAX was to GET/POST chat data to DB on server side, I didn't expect the Socket.io client would also use HTTP AJAX polling for socket.io but it did use HTTP polling over AJAX.

Here is brief explanation of the difference between HTTP long polling via AJAX and WebSockets only.

With long polling via AJAX, the server keeps polling WSGI server to check any new data. HTTP is not meant for keeping the connection open for the server to send frequent data to a client. The following is a sort of old way of implementing long polling via AJAX requests.

alt text

By using WebSockets, the server response (or data push) is more efficient. Server side does not need to keep sending no payload packet to a client. Its benefit is more distinctive as a server serves a large number of clients.

alt text

If you still need to use AJAX and Socket.io together, you could still force Socket.io to use Websocket only. The following method would even remove any initial XHR request to initiate Websocket between client and server. That is fantastc!

Server Side:

The 2nd line of the following can force the server to use WebSocket only.

module.exports = function(io) {
io.set('transports', ['websocket']); 
io.on('connection', socket => {
socket.on('join', params => {

Client Side:

The 1st line of the following is tells Socket.io client to use WebSocket only even though AJAX is used in the same client code.

const socket = io({ transports: ['websocket'] });
const postMessage = function(message) {
$.post('http://localhost:5000/api', message);
};

This simple trick works fine with the most modern web browsers except old IE9. It is recommend avoiding any XHR fallback and only use WebSockt transport.

Reference:
https://www.fullstackpython.com/websockets.html

Top comments (0)