Deno World
Published in

Deno World

Deno nuggets: WebSocket echo server

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

This story is a part of the exclusive medium publication on Deno: Deno World.

--

--

--

The one and only exclusive medium magazine with 200+ articles on Deno

Recommended from Medium

JavaScript Best Practices — Object Creation

Ensure Security for Open-Source Node.js Projects

Basic Routing with Express

Tech Stack 2019: Frontend Bundle Splitting

Create an RSS Reader with Vue.js and JavaScript

Docker images

How to Convert a Unix Timestamp to Time in JavaScript?

Build and Deploy NodeJs REST API On Firebase Cloud Functions in 5 Minutes !!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mayank Choubey

Mayank Choubey

Deno, Node.js, etc.

More from Medium

Deno nuggets: Simple hello world server

Deno nuggets: Write raw data on console

An ultimate guide to Deno

Deno nuggets: Use headers and query params like a plain object