Deno nuggets: WebSocket echo server

Mayank C
Tech Tonic

--

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to write an echo server over WebSocket?

> deno run --allow-all echo_client.ts
>>> 7a648426-5681-4f12-8b91-80f4068d90d2
<<< 7a648426-5681-4f12-8b91-80f4068d90d2
>>> 904b11d8-1dc5-441b-a011-6b6725776b41
<<< 904b11d8-1dc5-441b-a011-6b6725776b41
>>> 14986686-b002-4523-b882-8b83bc97805b
<<< 14986686-b002-4523-b882-8b83bc97805b
>>> 87969a7a-f370-467e-b748-0fda2306d426
<<< 87969a7a-f370-467e-b748-0fda2306d426

Solution

Imports

An import of serve API from Deno’s standard library:

import { serve } from "https://deno.land/std/http/mod.ts";

Echo server & client

Server

The echo sever takes the following steps:

  • Use serve API to create an HTTP server
  • Upgrade HTTP connection to WebSocket
  • At the very least, define an onmessage handler that would simply send the message back (ws.send)

Here is the complete code of the WebSocket echo server:

//echo_server.tsimport { serve } from "https://deno.land/std/http/mod.ts";async function reqHandler(req: Request) {
const {socket: ws, response: resp} = Deno.upgradeWebSocket(req);
ws.onmessage=m=>ws.send(m.data);
return resp;
}
serve(reqHandler, { port: 8000 });

Client

The echo client takes the following steps:

  • Make a connection to the WebSocket echo server
  • Define an onopen handler to send initial message to server
  • Define an onmessage handler that would send N-1 number of messages to the server
  • Close the connection when N number of messages are sent

Here is the complete code of WebSocket echo client:

//echo_client.tsconst sendMsg=(ws:WebSocket)=>{
const m=crypto.randomUUID();
ws.send(m);
console.log('>>>', m);
}
const ws=new WebSocket("ws://localhost:5000");
let msgCount=0, totalMsgs=Number(Deno.args[0])-1;
ws.onopen=()=>sendMsg(ws);
ws.onmessage=m=>{
console.log('<<<', m.data);
msgCount++<totalMsgs ? sendMsg(ws) : ws.close();
};

Sample run

Here is the output of a sample run (output is only logged by client):

> deno run --allow-all --unstable echo_server.ts> deno run --allow-all echo_client.ts 1
>>> 25c9bcdb-f6d5-4616-ace8-fd0c698c7544
<<< 25c9bcdb-f6d5-4616-ace8-fd0c698c7544
> deno run --allow-all echo_client.ts 3
>>> b91085ad-f2f2-4b27-81f1-de7f8bf22bdf
<<< b91085ad-f2f2-4b27-81f1-de7f8bf22bdf
>>> 1a4bb965-d004-4773-9e72-21ac2855f8fb
<<< 1a4bb965-d004-4773-9e72-21ac2855f8fb
>>> 5218022b-6b92-44d6-acde-3bd5d8198d69
<<< 5218022b-6b92-44d6-acde-3bd5d8198d69

--

--