Deno WebSockets Tutorial #5 - Broadcasting Messages
Skills:
API Design60%
Key Takeaways
Broadcasts messages using Deno WebSockets
Full Transcript
or rather than gangs so now what accepting messages right on the server from the clients and those messages are being turned into an object right here by using JSON pass on the JSON string that would get now this point what we want to do is take this data and we have a name property on that we have a message property on that as well we want to take that and we want to broadcast that message to all of the clients currently connected via a WebSocket so to all of the WebSockets currently inside this map so what I'm going to do is create a function now which does that so down here let me first of all say broadcast events to all clients now let me create this function I'm gonna call it broadcast event and that is equal to a function right here and inside this function as an argument we want to take in the event object now I'm gonna create an interface up here to describe what this object is gonna look like and this object has to have a name property which is a string and a message property which is also a string so let me create that I'm gonna say interface broadcast opt and that is going to have a name property which is a string and by the way if you want to learn more about interfaces definitely check out my typescript tutorial the link to that is down below and a message is also a string basically all we're doing is setting up a structure for certain types of objects and then right here where we have this function we're gonna say that the object that we receive in as an argument must follow the broad cast object interface so any object we take in as an argument must have these properties so now down here this thing does have those properties we have a name on it and we also have a message on it so what I'm going to do is I'm going to delete this line where we log it to the console and instead I'm going to call broadcast events and pass in that event object so then up here in the broadcast events function we want to cycle through our map and we want to send a message to each client via each of those WebSockets so let me now say sockets and we can use a method on this map called for each just like we can on arrays and inside here we're passing a callback function and we're going to find this function on every item inside that map now each time around we get access to the item which were called WS and that is going to be off type web socket because remember each item in here is a web socket the key is the ID but the item value itself is a web socket so we get access to each one of those as we cycle through them so right here we want to take that individual web socket that we're currently iterating and we want to send a message throw it to the browser so again we use the send method much like we did from the browser to send a message to the server we use this same send method to send a message from the server to the browser so we want to send a JSON string currently we have an object so let's now stringify that by saying jason dot stringify and pass in the object right here and that is it we're passing a JSON string as a message down this WebSocket to the browser so now every browser connected via their own web socket is getting that message on the front end now notice how the passing of the JSON object right here and the string defying of the subject back into jason right here in our case is a little bit redundant we're not really doing much in between we could have just kept it as a JSON string and then pass that back here instead of turning it into an object and then back into a string but we are checking that the message we broadcast contains a name and a message property and we wouldn't be able to do that if we didn't turn this into an object first and also this is good for if we wanted to do something else to the object in between these two steps such as an add a property or an ID property to each message all right so now we're sending that message back out to all clients all browsers let's now listen for that message on the front end and react to it so now after we send a message from the browser initially the server then takes that message over here and it sends out that message or broadcasts that message to every other browser that is connected via WebSockets to the server including the browser which originally sent the message to the server so we now need to set up a listener in the browser which listens for data coming back from the server down the WebSockets and then react to that by outputting that data in the dom that new chat right so we need to do two things we need to set up a listener which is listening for these events coming back down the WebSocket to the browser from the server then when we get one of those we need to fire a function which takes that data and outputs the event information to the dom so the message itself in a person who sent that message so let's set up this listener first of all and the way we do that is by taking our WebSocket instance which remember we have up here all right this ws thing and we can use a method on that called add event listener just like we would add to a form here now this event is called a message event so we're getting a message from the server and when that happens we fire a callback function now I'm going to call this callback function output message you can call it what you want but now I'm going to declare that up here so I'll say Const output message is equal to a function and inside this function we automatically get access to an argument which is the stuff we get back from the server when we get this message so let me just say evey for event and the first thing I'm going to do down here is just console dot log this event right so let me save that now and now if we go back over here and choose a nickname first of all enter chat now if I open up the console by going to console and send a message over here press n it goes to the server it should come back to us and then we log out the event that we get back from the server right so press send and we see this almost instantly didn't take long at all so this is the message event we get back and on here we get a data property so that's the stuff we actually want the name of the person and the message cents so what we could do is actually D structure that inside the parentheses so we could say we want the data from the event and now we're just going to get access right here to that data object so if I save this again and come and refresh then I'm gonna choose a name and I'm also going to type a message press send and now we get this so this is the JSON string that we need so the first thing we want to do is pass this and then extract these two properties from it so I'm going to say right here Jason dot pass and we want to pass the data right so now we have this object instead of adjacent string and then we want to extract from that the name and the message so let's use destructuring to do this as well so we want to D structure from here first of all the name and then the message property so now we have oops let's spell that correctly now we have access to both of those two properties they're the things we want to output inside a new li tag so what I'm going to do is set up a new template first of all using template strings so I'll say let template equal to template strings that's the baptists and that means we can output dynamic data easily inside this template string and we want this template to look very much like these Li tags up here so let me just grab that thing copy it and paste it all right down here like so so this is what we want I'm a template to look like but instead of this being Yoshi we want it to be this name so we can output a variable inside the template string by using dollar sign and curly braces and the variable itself which is the name and then down here we want to output the message so dollar sign curly braces message and that is all we need to do so now we're creating a bit of a template every time we get a new message back from the server so every time someone sends something we're going to get that back to the browser and we're going to create a template for that then we want to output that to the Dom so let's do that by grubbing this chat list right here remember that is this ul so we're going to say down here we want to get the chat list and we want to add to the inner HTML so plus equals meaning we're not going to replace this we're just going to add to it and we want to add to that the templates so this thing right here okay so now every time we get a new event a new message we're going to create a template and add that template to the UL so we're adding this Li tag to it now I want to get rid of this hard-coded stuff right here so to begin with it's just an empty ul and then only when we get new messages is it going to output a new Li tag in that so I've saved that now and let me come over here and I'll refresh and just try this out so choose a nickname Shan and then the message hey and now we can see we get this right here it was send another message then we see that message right here okay so finally I just want to test this out with three different browsers so imagine these are three different people all across the world at different points or visiting this website so the first thing right here they're going to choose a name Mario and Luigi and the third one right here thinks he's really clever and is gonna go into the dev tools and delete this form so he doesn't have to put a name in and then it's gonna come to the chat room and say actually the chat room is not going to be hidden so I don't want to enter a naming now remember we had a default value for the name which was a non anonymous for those that did not enter a name and that's what would happen if we tried to do something like this so I can see over here yo and then over here hey and you can see that updates in every chat room and then if I try to add a message over here it says an on so there we have it we have created this chat room with Dino and WebSockets now there is much more you could do here this is just a simple chat room so for example you could list all of the current users at the top or the bottom you could add timestamps or dates to each message you could develop private chats etc so have a play around and post anything you create down below in the comments and in the future I may do some kind of private chat tutorial using Dino and WebSockets building on from this as well so the my friends I really really hope you've enjoyed this series and if you have enjoyed it please don't forget to share subscribe and like that really means a lot and it helps out an enormous amount and if you do want to join the cause and support the channel you can do by clicking the join button on the channel home page or underneath the video or right down below you also get a little cool ninja badge next to your name in the comments Villa and its 99 pence or cents per month and I've also created several premium in-depth courses on udemy so the first one is modern JavaScript the second one is d3 and firebase and the third one is of UJS and firebase so if you want to take one of those all the links with the discounts automatically applied to them they're going to be in the video description down below so again thanks so much for watching and I'm gonna see you in the very next course you
Original Description
🐱👤🐱👤 JOIN THE GANG -
https://www.youtube.com/channel/UCW5YeuERMmlnqo4oq8vwUpg/join
----------------------------------------
🐱💻 🐱💻 My Udemy Courses:
+ Modern JavaScript - https://www.thenetninja.co.uk/udemy/modern-javascript
+ Vue JS & Firebase - http://www.thenetninja.co.uk/udemy/vue-and-firebase
+ D3.js & Firebase - https://www.thenetninja.co.uk/udemy/d3-and-firebase
🐱💻 🐱💻 Course Files:
https://github.com/iamshaunjp/deno-websockets
🐱💻 🐱💻 Other Related Free Courses:
+ TypeScript Tutorial - https://www.youtube.com/watch?v=2pZmKW9-I_k&list=PL4cUxeGkcC9gUgr39Q_yD6v-bSyMwKPUI
+ Deno Tutorial - https://www.youtube.com/watch?v=2iLeRzHvc10&list=PL4cUxeGkcC9gnaJdxuGvEGYQ9iHb8mxsh
Get denon - https://deno.land/x/denon
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Net Ninja · Net Ninja · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
GraphQL Tutorial #5 - Express App Setup
Net Ninja
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
GraphQL Tutorial #8 - Root Query
Net Ninja
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
GraphQL Tutorial #12 - Author Type
Net Ninja
GraphQL Tutorial #13 - Type Relations
Net Ninja
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
GraphQL Tutorial #18 - Mutations
Net Ninja
GraphQL Tutorial #19 - More on Mutations
Net Ninja
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
GraphQL Tutorial #23 - Create React App
Net Ninja
GraphQL Tutorial #24 - Book List Component
Net Ninja
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
GraphQL Tutorial #28 - Add Book Component
Net Ninja
GraphQL Tutorial #29 - External Query File
Net Ninja
GraphQL Tutorial #30 - Updating Component State
Net Ninja
GraphQL Tutorial #31 - Composing Queries
Net Ninja
GraphQL Tutorial #32 - query variables
Net Ninja
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
GraphQL Tutorial #34 - Book Details Component
Net Ninja
GraphQL Tutorial #36 - Styling the App
Net Ninja
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
Updated Vue & Firebase Course (Udemy)
Net Ninja
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja
More on: API Design
View skill →Related Reads
📰
📰
📰
📰
I let an AI write 6 WebGL hero sections — here's the one-CSS-variable reskin trick, and the honest review count
Dev.to · NeroTran
Real-Time Rails Without Turbo: Modern Reactive UIs with Inertia and DexieCable
Dev.to · Stefan Buhrmester
The Frontend Build Wars: Why Webpack’s Architecture Collapsed and How Rust Took Over
Medium · JavaScript
Persisting User Data in a No-Backend HTML App (localStorage Patterns)
Dev.to · PromptMaster
🎓
Tutor Explanation
DeepCamp AI