How to use WebSockets in a VueJS Website or App
Earlier this year we were rethinking our architecture at Bloverse where I work, we were building the mobile version on the application (we decided to go with a PWA for some reasons I’ll share in a later article).
Being a social news platform we needed the news feed to be real-time i.e feed gets updated immediately a post is published. I suggested we use the web socket communication model with the server, the engineering lead agreed to this and even took it further, he suggested that we use WebSocket as the primary communication model between the app and the server.
So let’s talk about WebSockets for a bit.
WebSockets, the what;
WebSocket is a communications protocol for a persistent, bi-directional data transfer between a client (a browser) and a server. This means that data can flow both ways, either from the client to the server or vice versa and the communication flow remains open (when an open connection is established) until closed either from the client or the server.
The technology is supported by most browser vendors, you can get more information on how many browser vendors support Websocket technology via here
WebSockets, the why;
Primarily it’ll be a good idea to prefer this communication model if you need realtime data on the browser and/or you need a persistent communication flow between the client (browser) and the server.
How to implement WebSocket in a Vuejs project;
The WebSocket API provides various methods 3 of the most important which I will focus on this article is onopen, onmessage, and onclose. I will write on handling WebSocket errors in another article using the onerror method.
So implementing WebSocket in your VueJs project is pretty straight forward and simple. navigate to your main.js file in your Vuejs project and use these few lines to initialize WebSocket connection to a server, open the connection, receive messages and implement any functionality upon close of connection;
Optionally, you can embed this entire code into a function and call it anywhere in your VueJs application, this can allow flexibility as you might need for just some specific parts of your application.
You can also send messages from the client to the server using the onsend method, example below;
It is also good to note that when the connection is made with the server and the browser is reloaded, the WebSocket connection closes and a new connection is created.
in subsequent articles, I’ll teach on the following…
- How to Implementing WebSocket using a nodejs server
- How to Websocket Error handling on the client
- And possible going in-depth into how Websockets work
Feel free to drop feedback, improve the knowledge and share.
Interested in AI and Computer Vision?
Read this: Introduction to computer vision with openCV