.NET 8 .πŸš€πŸ”₯: Building a Real-Time Chat App with .NET SignalR and React A Step by Step Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Hello friends thank you for watching this video I am Muhammad and today we're going to be discussing how we can actually build a realtime chat application utilizing nut signal R and react for our client application we're going to be going through step by step of what we need to do in order for us to build this application from the configuration to building the client Etc we're going to be discussing why do we need to utilize websockets rather than rest apis in order for us to build a real time chat application if you like this video please like share and subscribe it would really have the channel as well before we get started within the video I would like to thank my patreons for supporting me across this year now with that said grab your cup of coffee and let's get started so before we get started what we're going to be doing here we're going to be understanding why are we going to be utilizing websockets and not HTTP request and once we understand why we are utilizing web sockets we're going to be seeing the mechanism of how they work now let's take a sample of our chat application of two users want to communicate with each other we're going to be basically going through the architecture of how this application will communicate through HTTP request and then we're going to be seeing how they're going to communicate through websockets and we're going to be discussing the main benefits that we're going to be getting so let's say here I have my application and this application is going to be called my chat app and basically I'm going to have two users for the Simplicity of this example let's find the user icon so so here I'm going to have my first user and this user is going to be called Muhammad and I'm going to have another user and I'm going to call this user Lewis so I have my first user here and I have my second user here now what happen if these communication these two wants to communicate with each other we need a server so let's find a server and let's get this server here and basically my server is going to play the role of an entity intermediator so basically what's going to happen is whenever Muhammad wants to send a message Muhammad's going to do a post request and within this post request is going to go from my application to the server and then what's going to happen the server is going to be basically taking this request it's going to find a database so let's find the database and we're going to take this information and we're going to be storing it inside the database so now all of my information is already being stored in my database so then so this is going to be a post request so we can keep track of this and then when Lois wants to see their messages on their on their mobile phone or their application what they need to do they need to do basically another get request so they need to do an a get request and this get request is going to basically ask the server do you have any messages for me the server will say okay let me check the database the database is going to do a query we're going to find the results the results going to go send back to the server from the server they're going to be sent back to LS so we can see here that we're going to have a few different steps in order for us to get there so the first one is going to be posting the request from our application to the server the server is going to be doing another process which is going to be the uh sending the request to the database the database going to execute the query and get back the response then the server is going to send it back to the server in order for it to be processed and basically handle it properly and then we're going to be sending it back to the user directly in order for them to see those response so we can see here with a simple get request that we're doing going 1 2 3 4 five actually processes in order for us to get these messages and on the other hand whenever whenever Muhammad wants to send a message Muhammad wants to prepare the message so that's one we're going to be sending it to the server that's two then the server is going to store it inside the database execute the query and then we're going to be sending a00 so we have three steps running here and this is going to be also happening vice versa so let's say l want to send a message whenever we want to do a post request we're going to be sending into the server and so in the database so we can see here that this actually is creating a bit of of a lag between actually sending the Ser sending the messages and receiving them because what we're doing here is whenever we're doing a gut request is we're doing a pulling mechanism so what is a pulling mechanism a basically pulling mechanism is our application will do multiple get requests to the server saying like every 10 seconds every 30 seconds every 1 seconds we're saying do you have any messages for me the server will go check the database get the information back and send it to the user so this poing mechanism it basically allows the application to actually keep on checking if there's any new messages but this will not come without price because basically right now whenever we want to do any checks on the database to have our messages we need to do Bas execute five different steps in order for us to get there and to execute these five steps this going to cost a lot when it comes to server resources databas resources communication inbound and outbound traffic all of that going to be costly for us as well having the application keep on trying every 10 seconds as well is not a real time the best approach in order for us to utilize ping mechanism is basically to downgrade that ping time from 10 seconds to 1 second and if we downgrade from 10 seconds to 1 second that's only going to increase the server resource that we're going to be having cuz right now in this simple example we're going to having only two users imagine our application it's going to have around 10 million users using our application 10 million users doing sing 10 million requests every single time every single second to our application order for it to get the messages that's only forg not for posting the messages or doing any other changes that's going to require a lot of a big server form and all Fator for this and it's not really going to be easily scalable manageable etc etc so this is where we can see uh the there may be the potential downfall of utilizing HTTP request when it comes to having a chat application because all of this will have to come into place and basically a lot of resources were going to have to come into the server in itself in order for us to make this happen maybe this will happen for like a small application where you you know you have 10 hundred a thousand user maybe that will work but for a large St application that would definitely not work so what's the alternative options the alternative options let's just take a copy of this so we don't have to red th everything again and then we can adjust it so the alternative approach is to have something called Web sockets so let's remove these because we don't really have this I'm going to remove these for now and then we can read them whenever we need to so first of all in order for us to have un let remove this because we're going to be utilizing different connections what's going to happen when it comes to websocket connection let's add here websockets so it comes to web soet connection whenever my application is open I'm not add on anything I'm not asking for anything my application will basically initialize a new connection from the application to the server it will basically say hello server I'm the application who's being utilizing it I going to be utilizing this and I'm connected to you so we're going to say this red sorry in green which means that this application is already established a live connection so that's going to be the main thing with establishing a live connection between the chap application and the server similarly let's remove the spoiling mechanism uh the other user will also have to do the same thing whenever they want to connect they will connect to the server and they will like okay hi server I'm also going to be connecting so this is going to be another live connection so what we're doing here is we're establishing so between these two what we did is we have established a connection between our clients and the server so right now we did not send anything we just made aware that to the server that we have two clients currently connected to it and that's it and this server is basically uh connecting to thec between the two of them whenever one of these CLI disconnect the server will know that they have disconnected but for now what we're having here is we have established connection between these two clients to the server so what's happened then once we have established the the connection now we want to send a message so let's say now Muhammad wants to send a message to Lewis so again when whenever I want to do this I'm going to send the message directly to the server I'm just going to utilize it like this and I'm going to go do with this green color blue color so we know it it's a connection or a request coming in so now right now whenever a request is actually coming in directly from my client to the server as sending a message the server will directly notify the client that listen now there's a message coming for you that you need to actually handle so here we can see one of the main differences that we seen previously what we had to do is the client will have to keep on querying the server asking them for do you have any my messages do you have my messages on the other hand when it comes to up sockets we're actually doing the opposite once the client send a message to the server the server will directly forward this message to the client because they are already connected so the server will automatically realize that this message is going to go for this user and it will automatically forward it for them and that's going to be the main differences and when it comes to scaling this application this types of scalability is going to be much more easier to manage than having to manage a uh end point in order for us to have these messages now you you might say that you want to save those messages in your database you might want to keep a track of this that's completely fine you are able to do so but the main process behind them we are not relying right here in order for us to store these messes messages inside our database for the clients to be able to process these messages we're not relying at all the as soon as the message will come to the server the me the Ser the message will be forwarded to the right client by the server it will automatically know who is the client what's the and it will automatically forward the message so we are removing the bottl knck of actually relying on a database as the the main storage mechanism to keep track of all of the messages because in this example here what will happen if for example my message does not come into place or Bic my chat is not connected to me directly so what's going to happen here for example is whenever I do a get request I can have one messages I can have 50 messages or 100 messages getting it back here basically I'm getting every single message at a time but we can see here one of the main benefits of HTTP is we're going to be basically a to keep a track of all of these messages in case for example Lewis is not available online at this moment once they log in they will be able to get this messages similar concept will be can be implemented here directly through the database and all for us to do this that's going to be a bit of outside of the scope of today's video but the main idea is uh to understand today is that we are able to actually connect the clients with the server and back to the client directly through establishing connection and sending messages we're not going to be relying on polling so let us see again like very quickly let's use the AI diagrams P request so I'm going to ask the AI diagram here to generate a stro diagram illustrating plus fix illustrating HTTP requests versus sockets that's a very nice tool that will give me a diagram rather me than throwing it so now that my diagram is ready let us see the main differences so whenever we're doing a HTTP client request from the client to the server we're basically doing a HTP request when we're getting back the response the main differences when it comes to to websocket is going to be basically we're doing a head shake we're handshake we're establish the connection between the client and the server and once this connection has been established we're basically we're going to have a bidirectional data exchange and this B bidirectional data Exchange is what going to allow us to actually send and receive messages directly from our servers rather than actually trying to handle everything to the database in order for us to store and then doing the all the pulling mechanism and once basically when want to ter terminate the connection we close the connection and we get back that the a confirmation of our closer so this is going to be the main differences between handling the HTP request as well as handling the web sockets connection between the two and as you can see here that this is completely a different architecture when it comes to actually handling the commun ation this Bal bidirectional data exchange is going to be a really powerful tool in order for us to make sure that we have real time communication between our client and the server and between sending a messages so whenever we're sending a message to someone this message we're going to arrive instantly because we're going to have this by by Direction data exchange rather than having to rely on pulling mechanism between the clients and the serve in order for us to get the messages so now that we have covered the theory of this in general what we're going to be doing right now is we're going to be going through step by step creating a new web API creating the chat end points for it and then we're going to be creating a react app which going to be handling as our clients in order for us to actually create a full chat application so let's see this uh and how we can actually implement it so we're going to start first let me make this a bit let me zoom in a bit okay perfect so first thing that we're going to be doing is we're going to be creating our web API and it's going to be straight forward we already did this and we're going to be utilizing net new web API we're give it a name actually let's make sure it's a controller based it doesn't really matter but let use it and then we're going to give it a name as Formula 1 do chat uh service so this will create for me my web apis perfectly I'm going to open it up in ryer so now that I have opened it up in ryer what I want to do here is I want to open my terminal and I want to install a package and this package is going to be net add package microsoft. aspnet do signal R and basically signal R is Microsoft library and order for us to handle websockets it has been around I think since 2012 and it's only got better and better and basically signal R is going to be the main library that we're going to be utilizing in order for us to implement websockets within our within our application our cha application so now that we have installed it let's make sure it has been installed let's check our CS Pro and here as you can see that my asp.net signalr has been installed successfully perfect so now what I want to do is inside my application I'm going to create a new directory so add directory and I'm going to call this models because I'm going to have to create some models and inside this model I'm going to create a class and I'm going to call this user connection because basically whenever whenever a user wants to connect to my application what are they going to be providing they can provide like a username a password they can actually provide the chat room they want to utilize what we're trying to build here is we're going to be trying to build a very simplistic chat application which only going to be asking the user for their name and whatever chat room they want to join we're not going to be delving into the authentication and authorization and all of that we're going to be building a very straightforward application and for this we're going to be uing a model called user connection and within this model we're going to have two items so the first one is going to be a string and it's going to be the username of the user so username and the other one is going to be very simply the chat room that they want to join so once we have done that the next step is again inside my road directory I'm going to create a folder I'm going to call it hubs so what does hubs mean signal or hubs are basically a way that's going allow us to establish connection between our server as well as our clients and it's going to allow us to actually have this communication or bidirectional communication between our clients and the server and the hub's going to play a crucial role here because they integrate directly into the our asp.net core pipelines they're going to allow us to have a direct endpoint for every single chat that we have so we can for example have one hub for chat one H for notification one H for messages and all of that every single Hub will have its own configuration inside our. net application and all of those will you be utilizing the bidirectional communication in order for us to have the realtime communication so inside my Hubs folder here I'm just going to create a new class and this class I'm going to call it chat Hub and once I had the class Hub here I'm going to basically inherit from The Hub class and something to um keep attention to is basically whenever you want to inherit you're going to see here that there's going to be two types of hubs that's going to be available one inside the ASP Microsoft asp.net c. singlr another one inside the microsoft. asp.net singlr what we're going to be doing is we're going to be relying on asp.net core signal R if you put the asp.net some of the function not be available and there's going to be compatibility issu so make sure you utilize the as. core uh compatibilities so as we said a hub is basically going to allow us to send and receive messages uh between the clients because they are already connecting to uh connected to the to the server it's going to allow us the bidirectional connection and it's going to basically integrate within the middleware of our apis so once we have done that now let's create our first very simplistic endpoint within our signal R application uh or inside our chat applic so we can understand the concept of it so we're going to put public async task let's say join chat and I'm going to utilize the connection actually it's called user connection let's put user connection and I'm going to call it uh Co and here I'm going to be utilizing a wait and now I'm going to I'm going to write it down then I'm going to explain it so it's going to be clients all dot send a sync and here it needs to be the core one not the.net so send async and here I'm going to put the first one is going to be receive message and then we're going to put admin which is going to be the user who's sending this message back and we're going to be sending another argument say let's make it as string concatenation we're going to put con do username name has joined something like that okay let's put all this one on a different line so we're able to see it okay so let's explain what's happening here because basically what we have done is we have inherited from Hub once we inherited from Hub we got access to client and client as the description says allows us to actually invoke and send messages or receive messages from any of the clients that we are connected to it's a way where we can actually see every single client that's connected to our to our web server and basically from there we are able to access them and send them any information or receive any information that we want then we have the all all basically mean that we are actually targeting everyone if we don't want to Target everyone there's something called groups and this is something that we're going to be uh discussing in the next part of the video but for now we're just going to be sticking with all because it's the easiest one and then what we have within all is we have send a sync and send a Sync here mean basically this is then allow us to send messages and we're have here we're going to have a method we're going to have all the different AR ments so what is this method here uh that we have basically when a client send a message to the server and the clients will have to receive back a message where how does the server know to where it's going to rot this message because the client will also going to be utilizing or going to have a uh I want to say like a certain endpoint that's going to be living inside the client application was going to be responsible for handling all of the incoming uh messages and this is what we're doing here we're saying is the client will have a method or function inside the client application called rece message which going to be responsible for receiving the message that we're going to be sending so this is a very simplistic way to send a message to everyone who is connected to our application and the reason I wanted to Showcase that to show to show you how easy it is to get started with signal R and the websockets but we're going to be now taking it to our next step where we can actually see how we can actually create the code where a user will be able to join a specific chat group so let's put it here first public PNC task join spefic specific chat room and we're going to also take user connection Co NN and then we're going to put await groups do add to group async and I'm going to take the context do connection ID and then I'm going to take Co and. chat room so let's explain what's going on here as you can see in the before one we just send it to everyone but here we're introducing the concept of groups and groups is basically we creating like a sections inside our connections or basically we are organizing our connections into different um areas and what we're doing here is we're basically we're taking the chat group that the user has provided as a main area and what we're doing is we're adding that connection ID because every single connection that is uh let's go back to the diagram so every single connection that that is between the client and the server once it has been established and we got back the confirmation a unique connection ID is being created and what we're doing is we're relying on this connection ID in order for us to allocate every single connection to the chat room rather than us having to rely on a username for now uh and etc etc but for now to make it pretty straightforward and simple we're relying on this connection ID which is has been established directly once we have established the connection in order for us to rely on grouping those conversation so now that we have done that the next step is we're going to put await we're going to go back to clients. group and this here basically we need to specify the group that we want to send to and here as you can see it's it's requesting the group name I'm going to put connect connection chat room and then I'm going to put send async and from here again I need to specify the message that the client's going to be listening on I'm going to put receive message and then here I'm going to say the admin who's going to be sending this and I'm going to say lastly c. username has joined and let's put that channel name here that chat room name CN do chatro again let's do a quick recap on what we have done here so basically what we have done here is we first allocated the group assigned the group to that specific connection and then what we have done here is we have actually specified the uh send back a message to that specific room only rather than to all we specified the group we specified the name of it and then we have sent back the the same message so that's pretty straightforward and this is basically what we have done is whenever a user uh send a message or basically whenever a user join a group join a chat room you'll be able to see that Muhammad has joined this chat room or something like that so this is going to be the main purpose of this so now that we have done this I want to go to my program.cs and start configuring this so after our uh appbuilder what I want to do actually before our app builder whenever we have our Builder class I'm just going to put Builder do services. you signalr and this is going to be the main thing which going to allow us to actually utilize signal R inside our application and then the ACT step that we need to do is after our uh app builder build and before our app. run what we want to do is we want to put app do maphub and this is the Hub that we had before and we're going to put the chat Hub here and then we're going to say this is going to be the forward slash chat and this is going to be the end point that our application we're going to be able to listen to through up sockets in order for us to actually connect and this going to be chat not Char perfect so now that we have done this now we have at least some kind of a working back end for our chat appc application we're going to be adding more functionality down the road but this is like a initial working version of it I'm just going to put nut build now to make sure everything is building net run and we can see everything is running so now let's go back to our terminal and inside our terminal what we're going to be doing is we're going to be creating a react app so in order for you to uh to be able to utilize react you need to have nodejs so I'm just going to put node-- version I have already installed it but make sure you have the latest version or a recent version of node once you have done that next you need to do npm install Dash G create-react-app what we have done here we installed the package that's going to allow us to create a react application I have already done so before and it's already uh available on my machine for you it might take a bit longer and now once we have done that I can utilize the npx command to put create D react Das app and here I'm going going to Define give it a name which is going to be my Formula One do chat app okay I sorry I have capitalize it I should not have capitalized it so this will take also a few seconds a few minutes so let's wait until it's finished a few moments later okay perfect so now that our application has created successfully what I'm going to do I'm just going to go to it and I'm just going to open it up inside Visual Studio code so now that my application has opened in Visual Studio code we can see here that I have my source app which is perfectly I have everything that I need here let's zoom out a bit so the first thing that I want to do I want to open my terminal and I want to install some packages and the first one is going to be my signal r package to npm install at can you see this yeah uh Microsoft slash signal R okay perfect so now if I go to packages you'll be able to see that I have the latest version of Microsoft signal R perfect the other let's clear this the other library that I I want this bootstrap so I'm going to put again npm install react Das bootstrap bootstrap perfect so again as you can see I have bootstrap now and react book strap great so now that I have my pipeline configured to a certain extent now what I want to do is I'm going to go to my source I'm going to go to my app.js and what I want to do is I want to import my bootstrap Library so let me remove this I don't really need it now and let me add it here I'm going to put import bootstrap slash dist slash CSS slash bootstrap.min.css so now that I have this the next step is I'm going to actually start uh configuring this let's do some cleaning up so within this the first thing is I don't want anything from this app. CSS I'm going to delete it and let's make this really simple we don't really need any of this okay great and I'm going to even remove the class name we don't need it so now that basically I have a black canvas let let us start creating our application here so first things first I'm going to change this div with main actually let's keep the div I'm going to add main here and I'm going to add a container and inside this container I'm just going to add a row and inside this row I'm going to add a column and for this row I'm going to give it a class equal px-5 m-5 this is pure bootstrapping and pure CSS you don't really have to do this just for simply take I'm doing it I'm going to put sm12 and inside my call here I'm going to basically add an H1 and I'm going to say welcome to the F1 chat app and I'm going to give this one class class name actually it's going to be font Das weight Das light just to make sure everything is running I'm going to go back actually I'm going to keep this running inside my terminal I'm going to put npm start now it's running we can see it's running on Local Host 3000 I have a problem row is not defined oh forg I forgot to Define this so as you can see here inside my bootstrap I have my call I have and let add draw so now we can see it compiled successfully and if I come here now we can see that I have my welcome to F1 chut up perfect so now that we have done that and at least I have a running something inside react what I want to do is inside my source I'm going to create a new folder I'm G to call it components and inside my components folder I'm going to be creating the join chat room component inside my component I'm going to be creating the waiting room where basically you're going to be able to see the uh the two inputs where it's asking you to put your username and a password before you actually join the uh chat room so here I'm going to add a new file I'm going to call this the waiting room. JS and here what I want to do is I'm going to start first with const waiting room equal and we're going to fill this up later but for now let's keep it as is actually let's do it from now I'm going to have a math function called join chat room which is going to be utilized and now let's define my component before I do anything else I'm just going to put export default waiting room perfect so now that I have done this pretty straightforward now all I'm going to do here is first of all I'm going to utilize some states so const and this States going to allow me to store the username and the password going be username set username equal use State and it's going to be empty I'm going to put cost just's put username here not user I'm going to put here chat room set chat room also use State perfect so now that I have done that uh let us now create a form so I'm going to put return form on submit equal and I'm going to close the form and we'll import it later on basically here on submit what we're going to put is going to put actually let's create an event and within this event we're going to put e do prevent default which going to prevent the automatic refresh when we have this and I'm going to call the function that we have which is going to be join chat room and I'm going to pass the username and the chat room again we have not set the set this up yet but we're just doing we the work as we go and we're going to be modifying based on our need so now that I have my form submission now let's create our form we're going to have a a row and I'm going to give this a class name so put class name it's going to be similar px5 px-5 py -5 let's fix this here now I'm going to have my column and I'm going to be of sm2 so now that I have my column my row I'm going to build my form right now so I'm going to put form. group and inside my form group I'm going to put my form control and this is going to be a placeholder I'm going to put here username and I'm going to use the unchange method going to put e actually sub username and it's going to be the e. target. value and I'm going to close this let's put this in a new line okay so now that I have my username I'm just going to copy this I'm going to put here chat room and here's going to be set chat room and perfect so now I'm using the user States in order for us to actually set the username and a password in the chat room great so now I'm going to create my button so I'm going to put another call sm12 and here I'm just going to have an HR and then I'm going to put a button and we're going to put a variant of success so it will have green button the type it will be submit and okay I'm going to call this join perfect so now that I have done this the next step is I'm going to add this to my app.js so I'm just going to take waiting room I'm going to come here and what I want to do here is after my row I'm just going to add my component here perfect and as you can see it automatically been added if I go to my terminal where there's one error form is not defined so let's make sure we add this here okay let's add it in the import so here what I can do is I can add form and we can see build successful if I come here we can see now I have my chat room user chat room uh I have my username I have my chat room I have my join button it will not work right now because the function does not exist which is completely expected but at least now I can see my UI great now let's work on this functionality where we're actually able to join it a chat room so let's go back to our Visual Studio code and let's go to our appjs and let's start building this function here so inside my function app I'm going to create first first of all a state to manage my connection to make sure there's a connection or not so I'm going to put const con set connection equal use State and now here I'm going to creating my function and it's going to be const join chat room equal async username and chat room and basically what I want to do here I want to First do TR catch perfect now that I have my TR catch enabled I want to do a start all by establish my connection and to do that I'm going to put con Co equal Hub connection Hub connection Builder a few moments later it got hot here so I had to change my head to something a bit more comfortable cuz I have a bad hair day okay let's continue so now that we have created My Hub connection Builder let's actually build on that so it did not finish from here so what I want to do here is I want to add the following so first of all I want to specify my URL for the server so I'm going to put with with URL and here is going to be my URL so I'm going to go back to ryer and as you can see here my application is running on Port 5230 so I'm going to copy this and I'm going to put this as the URL that we're going to be communicating with let me remove all of this extra space perfect so now that we have done that now I want to specify the configuration for the loging so we're going to put configure logging and I'm specify the log level do information perfect and lastly I want to do the build so I'm going to build my connection great so now that I have done that the next step is I want to set up my handlers and handlers is basically here it's going to act whenever something is happening within my connection that I connected to it I disconnect from it etc etc so here I'm going to set up my Handler and what I'm going to do here is I'm going to put on do on and basically it means when I'm connected to it and this is the if you remember from here we had the receive message and this is basically I'm going to say this is going to be my receive message that's going to be uh the users going to be uh listening to so I'm going to call this receive specific message because we don't really want to send generic ones we only want someone join a specific message so I'm just going to make this like this and here I'm going to specify the message specific message and I'm going to specify here the uh user name and the message and basically what I want to do is I want to put for now console.log the uh message so I'm going to put message and here we're going to basically say whatever the message has been uh perfect so now that I have that the next step is I'm going to start my connection so I'm going to put await connection. start and then I'm going to invoke my message or basically invoke the endpoint that I currently have which is going to be a wait connection connection actually dot invoke and this invoke is going to have to match with the name of my method here so join specific room I usually have a rule to name them both the same thing so I'm actually able to understand you can name them whatever you want but basically this one has to refer to this so we're going to put invoke it's going to be join specific chat room service and I have to specify my username and my chat room and lastly I have to put set connection to co and basically what I'm doing is I'm setting up my connection inside my state so now if I go back to my terminal we can see here that chat room is not available so let's see where is that mistyped it here perfect we can see it's running okay now this is my joone chat room what I want to do is I want to pass my joone chat room to my uh waiting room and this is going to be the way the component will be able to know so I'm going to put here join chat room it's going to take the join chat room message so now we can see here that only the Hub connection and con is never used which is perfect I don't need this Hub connection I needed the Hub connection Builder and now this Con we're going to be utilizing later on when everyone want to send a message but nothing for now now if I go back to my uh react application I'm going to open the inspect so we can and check the console let me zoom in a bit into the console I'm going to go here to the console right now we can see there's a lot of errors I'm going to empty it out I'm going to refresh this that's fine I'm going to put username Muhammad chat room let's say team 44 join you can see we got an error let's see so there's an issue uh I did not put the new so let's see and I forgot to put the new keyword here now let's try this again let's clear this up and click on join okay we have a different error and failed to complete connection started let's say the network and I think I know the problem because the problem here right now is we need to set up the course because right now what we're doing is we're doing cross domain calling because we have we're having this running on Port 3000 where our application is running on Port uh 5230 so this one not going to be able to communicate with each other so for this we need to fix our cores in order for us to uh make it work so to do that it's going to be quite simple let's stop the application we're going to go to our program.cs and we're going to be adding our cores rules here so before we do the builder. build let's add the following we're going to put builder. services. add course and then I'm going to specify my options and it's going to be quite simple the options so we're going to put options do add policy and this policy I'm going to call it my react app and call it whatever I want and then I'm going to specify the Builder and then here I'm going to specify Builder do with origin specify the endpoint which is going to be Local Host 3000 so let's copy this and then what I want to do after this I'm going to say do allow any header allow do allow any method do allow any credentials and then once I have done that all I need to do it just let me copy my policy name which is going to be react up and here before this I'm going to put app do use sces and I'm going to specify my policy name so now let's run this again net run we can see it's running if I go back here clear this up join same thing let's see maybe we can get a with errors oh I missed this here so we need to add the chat because what we have done here inside our Hub is we have specified the endpoint and the endpoint here is forward chat so he would not specify that so that was another problem that you had to fix so let's try this again now let's clear this up and join let's stop the application and run it sometimes this will help and let's run this npm start and let's put Muhammad team 44 join same let's see the problem so now once we test it out we can see it's connected and we can see received the message Muhammad has joined team 44 and this is the exact same message that we currently had inside our Hub here we can see Muhammad has joined uh 44 perfect so now that we know exactly that our connection is working between our client and the server and that's what exactly what we need to do in order for it to make it work so first of all the the first problem was we did not add the chat here and the second one is we did not enable course inside our application so to enable course just make sure you follow the same thing and don't forget to remove the last forward slash because it will not work and make sure you add it into your uh app. scores uh functionality there so once we have done that the next step is so let's now let's go back to ryer what we want to do right now is we want to add some kind of persistency for our messages inside our web API in order for us to actually whenever a user will be able to join we're able to store those messages there and we're able to send them back so what we're going going to be doing is we're going to be creating an inmemory database inside our web API and it's going to be a dictionary and again it's pretty straightforward uh you can create your own uh database structure connect it to an actual database we're not going to be doing that we're going to doing an inmemory database just to make it simple and not make this video like 10 hours long so let's see how we can do this so inside ryer what I want to do here is I'm just going to create a new directory I'm just going to call it data service again it's going to be pretty uh straightforward and inside of this I'm going to create a new class I'm going to call it my uh shared DB I can call it whatever I want or in memory DB or anything that I want and here all I'm going to do is put public actually let's make it private read only concurrent dictionary and this dictionary is going to take a string and the user connection and then I'm going to call this connections and then I'm going to have a public concurrent dictionary string user connection underscore actually connections equal underscore connections forgot the arrow okay so now that I have this inside my program.cs all I'm going to do here is before the build I'm going to put uh Builder do services. add Singleton and here I'm going to add my shared DB now it's going to be available for me and now inside my chat I need to initialize it into my Constructor so I'm just going to here public private read only shared DB shared I'm going to put Constructor actually let's make it the short one so we can put public chathub shared DB shared undor shared equal to shared and now basically I can utilize my shared DB inside my application as much as I want so now basically what I have is I have created an inmemory database in order for me to store my uh connection incoming connection inside my uh dictionary perfect so once I have done that I want to build the functionality to send a message so let's do this here so public Asing task send message string message and this is going to be if undor shared. try. connections. try get value it's going to be context context. connection ID out user connection uh connection and then I'm going to put here a clients. group Co n.g group chat. chat room and then here we're going to put do Sund a sync I'm going to put receive message and then here we're going to put who the person who send it to which is going to be the username it's going to be con. username and the message that they have sent perfect so what we're doing right now here in order for us to send message is we still need to update this one so we can take advantage of this but basically actually let's update it and then we can discuss it so shared connections context do connection ID equal Z1 so what we're doing here is whenever uh someone joins our chatro we're adding basically their unique connection ID with their information to this in memory database and then when someone wants to send a message what they what we're doing is we're taking that connection ID because we don't really every single time we're doing a sending a message we want to get the usern name on the chat room etc etc because they already connected so this information should be available for us so what we're doing is once the ACT user connected we're storing this information inside this in memory database and then whenever we want to send a message we're taking their unique connection ID that has been established and then once we take this unique connection ID then we're actually utilizing it in order for us to send a message there so basically here what we're doing is we're tapping into this shared memory here so if you're using a database connection you need to utilize your database we're trying to extract value from our uh dictionary based on the connection ID and the value storing it inside our Co variable and that we're saying is similar to we have done before we saying groups uh chat the unique chat room which is this user belong to and then we're sending the message that receive specific message that we had before and this time instead of being the system who's sending it it's going to be the user who's sending it and we're passing the message that the user have sent so here we can see that this is how we can actually send the message so now that we have done that I want to go back to my angular application actually let's stop this and let's run it again again net run and I'm going to go back to my visual studio code and I want to add another Handler and this Handler will allow me to actually whenever there's a receive message I'm going to be able to utilize it so here I'm going to put Co dot on let's take the name of this receive specific message I'm going to put here username message and I'm going to put here the I need to create a messaging state so I'm going to put const messages set messages equal use State and we're going to initialize this to an empty array so here what I'm doing is I'm going to put set messages and it's going to be the message and actually let's make it in a different way because what I want to do is I want to pend it to the end of the messages because we're going to have a lot so I'm going to put set messages messages and one two three messages username and the message perfect so we created an array of objects for messages and what we're doing here every single time a new message comes in we adding to we're accessing the state we're accessing the messages and then we're basically we're appending at the end of the messages the new message that we currently have as simple as that so now in order for us to put everything together we're going to be needing another component and this component is going to going to be called let's go to it new file it's going to be our chat room. JS and it's going to be pretty straightforward so let's start first with const chat room equal and here we're going to be utilizing the messages we got had we just had some messages and I'm going to have a messages and I'm going to have here a div and inside this div I'm going to have a row and this row is also going to have the class name similar that we had before px-5 P y-5 perfect and then here I'm going to specify my column SM equal 10 so let's add column here and I'm also going to have my H2 here so I'm going to put H2 chat room and then I'm going to have to add another one which is going to leave it empty actually yeah let's make just this 12 actually we're going to need it now we're going to add a leave button later on so let's leave it as empty for now and then what I want to do is I'm going to add another row just to make it more consistent row and this row will we're going to give it the same class px-5 P y-5 and here all I'm going to be doing is call sm2 and then here I'm going to specify a reusable component which I'm going to be creating it's going to be called message container and it's going to be responsible for operating my messages and I can do this right now it's pretty straightforward let's create it now and then we can pass it pretty straightforward so once we have done that all I need to say here is export def default chat room so again before we forget message container let's create this directly here add a new file message container. JS and the message container is going to be pretty straightforward all it's going to do is going to put const message container equal it's going to take the messages and it's going to be return so return div and here we're going to put basically messages map message and index then from here we're going to return a table table stript and bordered and then from here we're going to put a TR and this TR will have a key equal to the index and lastly we're going to put ATD and thisd will contain basically my message and the message. username perfect so now if I go back here let's see what's going on still have everything running if I go back here I need to update now my app.js to reflect this so now what I want to do here I want to update this waiting room so basically what I want to do is I want to say whenever my connection is actually running I want to actually display my uh chat room if not I want to actually um display my waiting room so it's pretty straightforward to do so I'm going to put here if connection is not running I'm going to basically showcase my waiting room else oops let's make this here so if my connection is not running I'm going to showcast put this here I'm going to Showcase my waiting room as if it is running I'm going to Showcase my chat room and then in order for my chat room to work it's going to require the messages that I have and then here I'm going to pass my messages so now if I come back here to my terminal we can see here that I have problems so let's fix this message container is not defined so let's add this so chat room message container is not Define so let's add it actually let's try do this import message container from from message container so now if we go back to terminal one error it says imported is not found why is it not found oh I did not export it export default message so now we building successfully if I go back here let's reset this and let's do the username Muhammad and the chat room team 44 join join specific we have a problem with it so let's see this if I go to network okay let's see what the problem here okay we got an error okay so now that we are testing it so let's test it out let's clear this up going to put here Muhammad team 44 join and let's run this let remove those breaking points and let's run this and you can see I have a problem with my PP okay let's fix this error right now okay so the main way to fix this uh we had a typo here inside our chat room so I put three assets for messages instead of two and that was basically what halting um the mapping from working so now if we go back and we take a look at this let's refresh this page let's remove these logs and right now here what I'm going to do is I'm just going to put a username I'm going to say Muhammad and the chat is going to be team 44 I'm going to click on join and we can see I have joined the uh this chat room and I have got the message here that I have joined it successfully now what I'm going to do is I'm going to go to a different browser I'm going to open it and let me just put it here I'm going to go also to Local Host 3000 and it's going to be a different chat room so basically this is where I'm making a different user and what I want to do is I'm going to insert a different username I'm going to put LS and chatro is also going to be team 44 and now once I join here we can see directly I have received a message saying LS has joined this chat as well here I was able to propagate that L has joined the as well so this is a really cool thing so as soon as I clicked on join a message has went from my client to the server the server got the response and basically send it back to the chat all of that happened instantly between the two and basically I did not have to worry about it and let's see that something else so right now if I refresh this page and I put Lis but instead of joining team 44 I put for example team or I put Mercedes as a different chat group I click on join we can see that the the team 44 chat room did not get notified because L joined a different chat room and here we can see that separation of concerns between the two and how do they work and basically how they allow us to actually have unique different chat rooms based on the connection ID and based on the information that I'm providing okay great now let's continue developing this by adding the capability of adding a message so let's see how we can do that or sending a message so let's go back to let's go back to visual studio code and inside Visual Studio code I'm going to add a new file and I'm going to call this file message I'm going to call this file send message form. JS and this is going to be quite simple so I'm going to put const uh send oops send message form and this is basically going to take the send mthod function which we're going to be creating and basically from there we're going to be able to create our simple form that we need so I'm going to put const message set message and here we're going to be utilizing States so use State perfect and now all I'm going to do is going to return my form so form onsubmit it's going to be an event and from this event what we need to do is I'm going to put e do prevent default so we don't the page will not refresh and I'm going to call the send message and I'm going to pass the message attribute from the um use State and then I'm going to basically set the message again to uh null so basically it will be empty my text box so once I do that now I can actually focus on closing the form and what I need to do is I need to first of all specify my input group and I'm going to call give this a class I'm going to say it's mb3 and then I'm going to specify my input group text and I'm going to say this is chat quite simple and then after this what I want to do is I want to add my form control and let's give this information so I'm going to say on change what Bic I want to do I'm going to take my event I'm going to put set message and basically all is going to be e. Target dot value quite simple and then all I'm going to do after this I'm going to put value equal to my message so in simple terms this is where going to be handling my message input from the user and as soon as they input anything on change I'll capture it and I save it into my state and let's give one more thing at the end here which is going to be my placeholder and I'm going to say message type message type a message so now that I have done this inside my uh input group what I need also do is and I create a button and this button is going to be responsible for sending the message and then we're going to give it a variant and this variant is going to be green or actually blue for primary so we'll be able to utilize it to send I'm going to give it a type of submit and I'm going to make it disabled in case there's no message and the body of the button will be sent okay great once I have done that now I need to do an export default and I'm going to send message form okay perfect so now I'm going to go back to my app.js and what I need to do is I need to create a new uh function which is going to be responsible for sending a message so also I'm going to be creating it after the join function chat and here it's going to be quite simple I'm going to put const send message equal async messages and we're going to be basically actually message not messages we're going to be taking the uh we're going to do sorry try catch and we're going to put here catch and we're going to be basically taking the E and we're going to just simply do console.log in case anything goes wrong and then here what I'm going to do is I'm going to put my M that want I utilize so it's going to be await con do invoke send message did not create this on the server but we're going to be creating it now and I'm going to pass the message okay perfect so now that I have done this now let's go back to my uh actually let's finish setting up this and then we can set up my web server so what I need to do here is I need to pass the send message here so I'm going to go down to my chat room service and I'm going to add here send message equal send message and basically with this I'm actually able to uh take the send message and uh pass it forward so within the chat room what I need to do is I need to update this so it will take the send message as well and then what I need to do is after I have my uh message received so I'm going to add a new um column let's copy this and here I'm going to use my new component which is called message uh send message form and this will take my send message perfect so now that I have done this let us see if the UI will is updated so we can see here directly in the UI I have my chat I have my type my message and I have my button now if I put anything so now what we can see here we can actually send them so I'm going to say hello hi can say Muhammad said hi if I go to my other browser I'm going to refresh here I'm going to put leis again and I'm going to put the chat from Team 44 click on join it's different day I'm going to say hi Louis said hi Muhammad's going to reply say hello there and we can see it automatically let's make this a bit smaller so we can see it on both screens hello there we can see it updated then let's close this for now I'm going to say uh looking forward for the new season and Muhammad's going to reply yes very much so so we can see here directly we have two clients we're having a direct connection between them we have a directly chat application between them we're not relying on any thing between the two like a pulling mechanism between the client and the server we're relying on websockets to basically send my connections between my uh client my two clients into my server and back and basically what we're farming here is the connection identity so as soon as I refresh this all of this will gone because we're going to have a new connection uh uh identity generated once we actually authenticate and agree with the connection ID with the server but in order for us to make sure that all of this is actually working we relying this uh sample chat application on the connection ID that is actually being generated directly through once we establish the connection between the client and server in the real word scenario we need to rely on the username to capture the chat history we need to store them in a database there's a lot of different functional that we need to add this is just like a proof of concept of utilizing signal r with web sockets in order for us to make sure that we're actually able to create a real time chat application between two different clients and we can see here the scalability of this it will make it much more easier to scale on the long on the long run with millions and millions of subscribers or millions and millions of users using our application because basically we're only going to be sending messages whenever we have something available for us inside our uh servers so whenever a client send this rather than relying on long-term pulling that's going to happen whenever a client is basically just waiting and trying again to receive a message I hope this video was helpful uh if you have any other questions please let me know please put them in the comments down below and I make sure to address them thank you very much for watching and have a great day
Info
Channel: Mohamad Lawand
Views: 13,600
Rating: undefined out of 5
Keywords: dotnet, react, RealTimeChatApp, signalr, reactjs, .net development, websockets, websocket, ChatApplication, FullStackDevelopment, CodingTutorial, JavaScript, C#, csharp, WebDevelopment, AspNetCore, Tech tutorial, SignalR React Integration, Programming, software development, web app tutorial, frontend backend integration, modern web technology, Real Time Chat, SignalR Guide, React Development, Full Stack Tutorial, Interactive Web Application, c# and signalr
Id: pvi_ZS_PrSc
Channel Id: undefined
Length: 60min 13sec (3613 seconds)
Published: Sun Dec 31 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.