Websockets

With some free time on holiday, I took the opportunity to answer some questions about Websockets, which ended up being a lot of fun.

Websocket is a communication protocol built on top of a single TCP connection that was proposed in RFC 6455, it’s a full-duplex protocol, that is, it allows data to be received and sent by both parties simultaneously.

Therefore, it is the ideal protocol for situations that require real-time communication, such as chats.

Websockets connections are initiated over HTTP via the Upgrade header, which is used to indicate that the client wants to change the protocol used on the connection. The Upgrade header can also be used to upgrade to other protocols, such as HTTP/2.

Connecting to a Websocket endpoint is quite easy, since most browsers already support the Websocket API. For example, here’s how you can connect to a Websocket server using Vue:

<script setup lang="ts">
import { onBeforeUnmount } from "vue";
import { WS_URL } from "./config/env";

let ws: WebSocket;
let message: string;

function handleWS() {
  ws = new WebSocket(WS_URL);

  ws.onopen = (e) => {
    console.log("connected", e);
  };
  ws.onmessage = (e) => {
    console.log("message", e.data);
  };
  ws.onclose = (e) => {
    console.log("disconnected", e);
  };
}

onBeforeUnmount(() => {
  ws.close();
});

function sendHello() {
  ws.send(message);
}

handleWS();
</script>

<template>
  <input type="text" v-model="message" />
  <button @click="sendHello">Send hello</button>
</template>

With a Websocket object, you can then handle the connection events, such as onopen, onmessage, onclose, and onerror.

Anyways, there’s a lot more about Websockets, but I think that’s enough for today.

edit this on github