WebSocket and WebWorker

Aravind S
4 min readMar 20, 2019

--

Photo by Markus Spiske on Unsplash

WebSocket:

When we hit a URL from the browser client, this request got the backend server in the form of HTTP or https. Whenever a request sends to the web server, a TCP connection is established and this connection will be closed when the client receives a response from the web server.

HTTP or HTTPs client-server handshake

Web sockets are defined as bi-directional communication between the servers and the clients, which mean both the parties communicate and exchange data at the same time. Websockets are created using ws:// or wss:// unlike the http:// or htpps://

WebSocket Communication

So the main difference is HTTPs are unidirectional where the sender has to trigger a request to get data, but WebSockets are bidirectional where the sender or receiver can send the data. The best example for this is a chat application. Suppose you sent a Hi to your friend, then you are sending a request to the server. But at the same time server will push the data to your friend’s chatbox. How WebSocket are achieving this means, they don’t close the connection once established.

Let me share one example where WebSocket is used. If you are using VS code, for UI development, then you may have used the Live Reload plugin. This plugin actually uses WebSocket for Live Reload. Here is code for that

if ('WebSocket' in window) {
(function () {
function refreshCSS() {
//Function to refresh CSS
}
var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
var address = protocol + window.location.host + window.location.pathname + '/ws';
var socket = new WebSocket(address);
socket.onmessage = function (msg) {
if (msg.data == 'reload') window.location.reload();
else if (msg.data == 'refreshcss') refreshCSS();
};
if (sessionStorage && !sessionStorage.getItem('IsThisFirstTime_Log_From_LiveServer')) {
console.log('Live reload enabled.');
sessionStorage.setItem('IsThisFirstTime_Log_From_LiveServer', true);
}
})();
}
else {
console.error('Upgrade your browser. This Browser is NOT supported WebSocket for Live-Reloading.');
}

Here is the list of the events of WebSocket.

socket.onopen — This event occurs when the socket connection is established.
socket.onmessage — This event occurs when the client receives data from the server.
socket.onerror — This event occurs when there is an error in communication.
socket.onclose — This event occurs when the connection is closed.

Here is the list of the methods of WebSocket.

socket.send() — The send(data) method transmits data using the connection.
socket.close() — The close() method would be used to terminate any existing connection.

Check out another example at the real-time example at pro.coinbase.com

Read more about it here: https://www.tutorialspoint.com/html5/html5_websocket.htm

WebWorker

When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background. Here explaining how we can use WebWorker for creating an offline page.

Step 1: Check Registers a new Service Worker

if ("serviceWorker" in navigator) {
navigator
.serviceWorker
.register("service-worker.js")
.then(function(reg) {
console.log("Registred with scope: ",reg.scope);
})
.catch(function(err) {
console.log("ServiceWorker registration failed: ", err); });
}

Step 2: On the service-worker.js, we can initialize the cache and add files to it for offline use.

let cacheName = "myappCache";
var filesToCache = [
"index.html",
"js/site.js",
"css/style.css",
"images/favicon.png",
"images/desktop-bg.jpg",
"images/mobile-bg-copy.jpg",
"images/og-image.jpg"
];
self.addEventListener("install", function(e) {
e.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll(filesToCache);
})
);
});

what ExtendableEvent.waitUntildoes, and what the caches object is — The service worker does not install until the code inside waitUntil is executed. It returns a promise — this approach is needed because installing may take some time, so we have to wait for it to finish. caches is a special CacheStorage object available in the scope of the given Service Worker to enable saving data.

Step3: On the service-worker.js, we have an activate event. Once a new ServiceWorker has installed & a previous version isn’t being used, the new one activates, and you get an activate event. It can be used to clear out the old cache we don’t need anymore.

self.addEventListener("activate", function(e) {
e.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(
keyList.map(function(key) {
if (key !== cacheName) {
return caches.delete(key);
}
})
);
})
);
return self.clients.claim();
});

Step4: On the service-worker.js, we have a fetch event, which fires every time an HTTP request is fired off from our app.

self.addEventListener("fetch", function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
if (response) {
return response;
} else {
return fetch(event.request)
.then(function(res) {
return caches.open(cacheName).then(function(cache) {
cache.put(event.request.url, res.clone());
return res;
});
})
.catch(function(err) {
return caches.open(cacheName).then(function(cache) {
return cache.match("/offline.html");
});
});
}
})
);
});

Here, we respond to the fetch event with a function that tries to find the resource in the cache and return the response if it’s there. If not, we use another fetch request to fetch it from the network, then store the response in the cache so it will be available there next time it is requested.

That’s it! Our app is caching its resources on install and serving them with fetch from the cache, so it works even if the user is offline. It also caches new content whenever it is added.

Read More about it here: https://jakearchibald.com/2014/offline-cookbook/

Happy Reading!

--

--