Two ways to connect WebSocket in Vue 3

Two ways to connect WebSocket in Vue 3

2023-04-21
4 min read

Overview

WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. Thus, WebSocket will help you to send a data to server and receive event-driven responses without having to poll the server for a reply.

Setup Server.

If you already have WebSocket server or know any urls, just pass this section. This sections is going to talk about how to setup Websocket server. Server is consist of Node.js and Typescript. Click link to see more details.

Setup Node.js and Typescript

bash
npm init -y
npm install @types/node --save-dev
npm install typescript --save-dev
npm install ts-node --save-dev

npm i ws
npm i @types/ws --save-dev

ws is Node.js WebSocket library. It helps you to develop WebSocket server in Node.js.

Code

typescript
import { WebSocketServer } from 'ws';

const Port = 5174

const ws = new WebSocketServer({
    port: Port,
});

ws.on('connection', (ws) => {
    ws.on('error', console.error)

    ws.on('message', (data) => {
        console.log(`Received: ${data}`);

        ws.send('Send back');
    });

    ws.send('Hello World');
});

console.log(`New WebSocket sever starts at ws://localhost:${Port}`);

Make a file named websocket.ts. Copy and Past Code into file that you just created. If you type command ts-node websocket.ts, you will see ws://localhost:5174 log in your command line. WebSocket server will starts with ws or wss according to your secure setting. They are very similar with http and https

First way: ws package.

Implement WeSocket client a same package that we used in Server. ws provides client utilities. Click link to see more details.

Installation

bash
npm i ws
npm i @types/ws --save-dev

Install the package into your client (Vue 3 project) before you start.

Code

vue
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'

const webSocket = ref(new WebSocket('ws://localhost:5174'))
const messageFromSever = ref('')
const isConnected = ref(false)

webSocket.value.onopen = (e) => {
  console.log('onopen', e)
  isConnected.value = true
  webSocket.value.send('Hello I am testing')
}

webSocket.value.onmessage = (e) => {
  console.log('onmessage', e)
  messageFromSever.value = e.data
}

webSocket.value.onclose = (e) => {
  console.log('onclose', e)
}

webSocket.value.onerror = (e) => {
  console.log('onerror', e)
}

onBeforeUnmount(() => {
  webSocket.value.close()
})

</script>
<template>
  <div>
    <div>
      Connection: {{ isConnected ? 'Connected' : 'Disconnected' }}
    </div>
    <div>
      From sever: {{ messageFromSever }}
    </div>
  </div>
</template>

Create any name vue file then copy and past the code. The isConnected variable is used for checking connecting between WebSocket server and client success. The messageFromSever variable will contain a message from server. Depending on data from server, it could not be string type. (It will be string if you followed the server section)

Open and error

onopen event will fire when client successfully connect with WebSocket server. onerror message will be fire when connection meets any errors on connection.

Send data

send function will send a message to WebSocket server. send allows string or a binary format such as Blob, ArrayBuffer. The message from server is contained in e.data. If it could be any type according to data.

Rate Limiting

In order to prevent to make your network connection slow, you can check buffer amount.

typescript
const interval = setInterval(() => {
  if (socket.bufferedAmount == 0) {
    socket.send('some data...');
    clearInterval(interval);
  }
}, 100);

every 100ms examine the socket and send more data only if all the existing data was sent out

Receive message

onmessage is event that receive message from Server.

close handling

onclose event will fire when client close connection with server. Close event includes code (number), reason(string) and wasClean. wasClean is boolean type of data used for checking it's cleaned up.

Second Way: useWebSocket in vueuse module.

vueuse module will be used in second way. The vueuse is collection of Vue composition utilities. Although Vueuse module has a plenty of utilities, we will use useWebSocket in order to handle WebSocket connection.

Installation

bash
npm i @vueuse/core

Install module before you use it. It contains types, so you don't need to install types. If you would like to read documentation first, here is the link.

Code

vue
<script setup lang="ts">
import { onMounted } from 'vue'
import { useWebSocket } from '@vueuse/core'

const { data, status, send } = useWebSocket('ws://localhost:5174')

onMounted(() => {
  send('Hello I am testing')
})

</script>
<template>
  <div>
    <div>
      Status: {{ status }}
    </div>
    <div>
      From sever: {{ data }}
    </div>
  </div>
</template>

Status has three values including OPEN, CONNECTING, CLOSED If you pass autoReconnect option, it tries to reconnect on erros automatcally

typescript
const { data, status, send } = useWebSocket('ws://localhost:5174', {
  autoReconnect: true,
})
typescript
const { status, data, close } = useWebSocket('ws://websocketurl', {
  autoReconnect: {
    retries: 3,
    delay: 1000,
    onFailed() {
      alert('Failed to connect WebSocket after 3 retries')
    },
  },
})

You can prevent time of calling and delay with options.

Open

Once you enter the page, useWebSocket will try to connect with WebSocket in link automatically.

Send

send is the function that sends a message to WebSocket server.

Receive message

Whenever you receive message from server, data will be changed to message that came from server.

Close

You have to close connection in onBeforeUnmount By contrast, you are not required to call close() function before you leave the page. The reason is that useWebSocket calls close() if you don't call any close().

ref

Free open source project made by Youngjin