Implementing WebSocket Client and Server on ASP.NET Core 6 | HOW TO - Code Samples

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to Startup hack today we are going to talk about implementing websocket client and server on esp.net core so let's Jump Right In make sure to check out the link down below because we always provide the code samples that you can pull down and follow along so you can see in our project do you want to earn a hundred thousand dollars a year do you want to become a software developer within just three months with our amazing cards and awesome tutors you never have to worry about getting stuck we help students to learn skills that companies want to hire we are startup hack don't forget to subscribe our channel so let's get started alright let's start with creating a websocket server for this we need to select asp.net core empty application and click next and name it WS server and select.net 6.0 as a long term report and created after the project is generated we will get ourselves a bank asp.net core 6.0 template we can delete the unused hello world and point also modify app.run to run async to use websocket in our project we call the use websocket function on our web application instance for our convenience we can also call builder.webhost Dot use URL method to set the URL and port for our server in this video I am using localhost as the URL with Port 6969 then we need to map an endpoint to be used for our websocket server we will do this by using app.matmap third with our route and contacts which will be used for handling websocket here we will use WS as the websocket root inside the context we will configure the endpoint to accept only websocket connections by implementing a check of context.websockets dot is websocket request then set the status code to bad request 400 if it is not a websocket request after checking the connection is a web socket request we can use the this code to refine the current connection instance to send a message we can use send async method on our websocket connection instance the sand async method accept array segment by websocket message type enum pool of end of message and cancellation token as its parameter to send a text to the client we need to convert it into a buy diary and create a array segment byte with it so here's the example now let's make our websocket server return the current time in hour minute seconds format every one second to the client we can do this by wrapping the logic that we use to send messages inside a while true Loop and using thread.sleeve 1000 to implement the one second delay we will also check to only send the message when the websocket state is open and break the loop if the state is closed or aborted voila our websocket server is done now to check it we need a websocket client to create a websocking client we need a console app so we will be creating console app and name it WS client and it should also be in.net 6 created to create a websocket client we can use the client websockets from system.net websockets to connect with a websocket server we can use the connect async method with the URL and cancellation token now let's create a task to receive a message from the server while the connection is alive to receive the message we can use the receive async method on our websocket client instance the receiver async method accept array segment board and cancellation token to receive a message we need to create a new byte array as a buffer which we will use to create the error segment byte for cancellation token we will use cancellation token dot run remember that the result is still in buy diary to display it as a string we need to encode it first we can do it by using encoding.utfa dot guided string method lastly we need to check if the connection is not closed before processing the result we can do this by checking if the message type is not closed so here is the whole final code of websocket client now I'm going to run websocket server and websocket client so after that it will show on the client side so I'm running the websocket server so when I run the server and the client so it is showing the current time on my console on the websocket client all right let's move towards another topic handling multiple websocket let's Implement a simple chat room application with websockets by modifying our previous code to keep track of multiple websocket Connection in the websocket server we can store the websocket connection instance in a list to broadcast a message to every client we can create a function that calls the sand async method with every websocket instance that is open in the list to emulate a chat room we will add a username for the connected client which is fetch via the request parameter we will also broadcast whenever a client is connected now let's handle the process of receiving messages similar to the clients are we can call the receive acing method with a buffer while the socket state is open let's wrap this luggage into a function receive message now to broadcast the received message to other clients we need to modify our receive message function let's add action websocket receive Reserve by handle message delegate in our receive message function parameter call the handle message delegate by passing the result of receive acing and buffer final code looks like this here people joined the room also they want to left the room they can use that by Broadcasting here are the receive message method and broadcast method over here so we will be now considering modifying web socket client to handle Sending message to the server alright first add the username input which will be used in the chat room so it will take the input for the username over here all right create a task to handle sending the message to the websocket server here we will read the input from the user and send it by calling sand async on the client websocket instance we will add a check to exit the chat room with exit we have both receive and messages tasks running asynchronously finally handling the client's exit by sending close async whenever one of the threads is finished then await until all thread is finished to close the program so here's the code whenever one of the thread is finished then await until all thread is finished to close the program alright let's run the project for running it will ask the name it's connecting to server one user is connected all right I have two users connected at same time so if Spencer say hi and John say also hi it will show to all users at a time so here's the example you are seeing right now thank you for watching this video I hope you learned the concept of how to implement websocket client and server in asp.net core so don't forget to subscribe our Channel and hit the Bell icon for latest updates to joining our course you can simply go to our website called startuphack.com thank you
Info
Channel: STARTUP HAKK
Views: 9,350
Rating: undefined out of 5
Keywords: software development, software engineering, software developer, software engineer, custom software development, software myths, azure, azure engineer, azure development, Microsoft azure, c#, dotnet, dotnet coding, dotnet coding bootcamp, html, javascript, LearnToCode, Lean to Code, coding, coding bootcamp, become software developer, azure devops, .net core, asp.net core, How to, Code Samples, Code Sample, Coding tutorials, Coding Tutorial, websockets, client server, websocket c#
Id: SYoACrFXNRE
Channel Id: undefined
Length: 8min 51sec (531 seconds)
Published: Mon Oct 02 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.