DEV Community

Cover image for Chat made with Deno
Assis Ferreira
Assis Ferreira

Posted on

Chat made with Deno

There are few days that was launched the Deno, a new JavaScript and TypeScript runtime built in Rust. In this project we use that technology to create a simple web chat.

The project code is hosted in that repository: https://github.com/assisfery/WebSocket-Chat-made-with-Deno

Alt Text

Web Server

Here we load the Web Server module to host our index file.

import { listenAndServe } from "https://deno.land/std/http/server.ts"; listenAndServe({port: 8000}, async(req) => { if(req.method == "GET" && req.url == "/") req.respond({ body: await Deno.open('index.html') }); }); 
Enter fullscreen mode Exit fullscreen mode

WebSocket Server

We load the WebSocket client and WebSocket Serve module,
to listen client message and broadcast to every user connected.

import { WebSocket, WebSocketServer } from "https://deno.land/x/websocket/mod.ts"; const wss = new WebSocketServer(8080); wss.on("connection", function (ws: WebSocket) { ws.on("message", function (message: string) { console.log(message); wss.clients.forEach(function each(client) { if (!client.isClosed) { client.send(message); } }); }); }); 
Enter fullscreen mode Exit fullscreen mode

WebSocket Client

In our index file we handle our WebSocket client using JavaScript native API.

var userName = null; var clientWS = null; function main() { if($("#usr").val() == "") { swal("Warning", "Empty name!", "warning"); return; } userName = $("#usr").val(); $("#loader").show(); $("#sign-in").hide(); clientWS = new WebSocket("ws://localhost:8080"); clientWS.onopen = function (event) { swal("Conneceted", "Connected successfully!", "success"); $("#loader").hide(); $("#chatbox").show(); }; clientWS.onerror = function (event) { swal("Error", "Something happens!", "error"); $("#chatbox").hide(); $("#sign-in").show(); }; clientWS.onclose = function (event) { swal("Closed", "Your connection was closed!", "info"); $("#chatbox").hide(); $("#sign-in").show(); }; clientWS.onmessage = function (event) { console.log(event.data); var message = JSON.parse(event.data); if(message.type == "message") { if(message.user != userName) $("#message-box").append('<div><div class="bubble"><b>' + message.user + ': </b>' + message.content + '</div></div>'); else $("#message-box").append('<div class="text-right"><div class="bubble bubble-info"><b>' + message.user + ': </b>' + message.content + '</div></div>'); } }; } function send() { if($("#msg").val() == "") return; var message = { type: "message", user: userName, content: $("#msg").val(), }; clientWS.send(JSON.stringify(message)); $("#msg").val(""); } 
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
neisha1618 profile image
Neisha Rose

This is my introduction to Deno and Rust. amazing