Beginner
clideployweb
Outbound WebSockets
Opening a WebSocket connection for real-time, bi-directional communication with Deno is very simple.
First we need to use the WebSocket constructor to initiate our connection to an external server
!--frsh-copybutton:1-->
const socket = new WebSocket("ws://ws.example.com");
Before we do anything with the websocket, we should wait to make sure that we are connected. We can do so by listening to the "open" event.
!--frsh-copybutton:2-->
socket.addEventListener("open", () => {
We can read the "ready state" of our instance. This determines if we are able to send messages. The ready state for open should be 1.
!--frsh-copybutton:3-->
console.log(socket.readyState);
We can now send messages to the server. The messages can be of the type string, ArrayBuffer, Blob, or TypedArray. In this case we will be sending a string
!--frsh-copybutton:4-->
socket.send("ping");
});
We can handle messages back from the server by listening to the "message" event. We can read the data sent by the server using the data property of the event.
!--frsh-copybutton:5-->
socket.addEventListener("message", (event) => {
console.log(event.data);
});
Run this example locally using the Deno CLI:
deno run --allow-net https://examples.deno.land/websocket.ts
Additional resources: