Go WebSocket Tutorial with the gorilla/websocket Package

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Question. How do you determine how many sockets a single server can handle at one time? I am thinking if I deploy my Rest API in the cloud, and want real time updates using websockets, there has to be a way to ensure my 1 instance that I pay so much a month for can keep all those sockets open. Does the back end possibly "pause" sockets to handle a lot more of them, so to speak? Or do you just have to spin up (and pay for) a lot more instances to handle say 1000s of simultaneous connections?

Is it common for the client developer to read docs that indicate a socket will only stay open for say 10 seconds, then close, so the client should listen for a 500 or 400 or something, and re-establish the connection? Is that a typical work flow for using sockets so you can handle a lot more without having to spend a ton scaling to handle the load?

👍︎︎ 2 👤︎︎ u/[deleted] 📅︎︎ Mar 17 2019 🗫︎ replies

Great video! Thanks for this.

👍︎︎ 1 👤︎︎ u/Jaeemsuh 📅︎︎ Mar 17 2019 🗫︎ replies

Im pretyy new in golang, and everytime I do sth I struggle to find any decent sources or tutorials and when I finnaly manage learnbit by myself, there come those great tutorials. Why cant I save up time sometimes...

👍︎︎ 1 👤︎︎ u/Qizot 📅︎︎ Mar 17 2019 🗫︎ replies

I'm learning golang for web. Nice tutorial, thank you.

👍︎︎ 1 👤︎︎ u/alfredisabug 📅︎︎ Mar 18 2019 🗫︎ replies
Captions
hi everyone is Elliot from tutorial h-net and unless the to do we're gonna be looking at how you can use WebSockets within your own goal based programs to do some really cute real-time stuff now by the end of this tutorial we will have covered what WebSockets are and we'll also have covered how you can build a simple web software application in go.they connects to our front-end JavaScript application now the filter expression Alessa toriel will be available on my website and I'll be leaving a link to this in the description below so what are WebSockets well WebSockets are upgraded HTTP connections that love until the connection is killed by either the client or the server it's through that's WebSocket connection that we can perform duplex communication which is just a really fancy way of seeing we can communicate to and from the server using a single connection now the real beauty of WebSockets is that they use a grand total of one TCP connection and all the communication has done over this single long left TCP connection now this drastically reduces the amount of network overhead required to build real time applications using WebSockets as there isn't that constant pooling of HTTP endpoints required cool so let's dive into our code editor of choice and start programming now as you can see here I've got incredibly simple cool program up and running already and I can run up within my terminal by calling code run window cool cool now for the purpose of this tutorial I'm gonna be using cool modules so in order to do that we'll need to initialize a project by calling go mod and it and the location of our repository which is gonna be cool WebSockets tutorial like so that will create a go mod file and then from there we'll be able to import the various packages that we're gonna be using and that's tutorial okay so now that we've got basic go program up and running let's start off by creating a simple HTTP server that simply returns hello world when we had set on localhost port 8080 now it first thing I'm going to do is just above my main function I'm going to create a new function called set up routes and with an S I'm gonna set up a few routes so handle funk and the home page rip and that's will map to home page function that will define in just a second and the next route we're gonna do is handle funk and WebSocket which will go to our web socket can point function now because we're gonna be using the HTTP package we're gonna have to import it up at the top here by doing net slash HTTP and finally and I mean function we want to call the set up roots function cool so that is no complaining about messing with these two functions so let's define them now and we'll start off at the home page function which is good it's going to be a nice and simple function takes in the HTTP response writer and pointer to HTTP requests and we're simply going to return hello wattle to our home page string to the response writer like so cool and let's now do the WebSocket endpoint function which is going to take in the same arguments so response writer and another pointer to HTTP request and again we just want to FM t 2f print F to the response rater we're gonna say web socket endpoint awesome so one final thing we'll have to do to kick off our web server as to lesson so I'm going to do log table fatal and I'm going to do HTTP lesson and sir and we're gonna do this on port 8080 as I said before and we're gonna pass in an L as the second parameter here and if we save that and come into our terminal we should be able to kick this off by taking call run min cool perfect so that looks like it's up and running and just a double check we can come into the console and that localhost 8080 and you should see that homepage as successfully returned so we've never got a basic web server that we can build our WebSocket endpoint on top of now in order to create a WebSocket endpoint we're effectively going to need to upgrade an incoming HTTP connection and we're gonna be doing this using the Gorillaz slash WebSocket package so if I come back into my code editor and I'm gonna come up to the top here and I'm gonna do the following so important yeah hub comm slash guerrilla slash Oh now the first I'm going to do is to define an upgrade er so VAR operator equals WebSocket dot operator and this will be a stroke that takes in the read buffer size which is just going to be a thousand 24 and it's also going to take an array buffer size so right buffer size cool now the next I'm gonna do is calm down and to this WebSocket important function I'm gonna simply remove what we had there before now and here I'm gonna want to do the following so upgrader dot check origin and this week what function which takes in the pointer to the HTTP request and returns a bill and I'm simply going to return it true for now this is just a quick and dirty way of saying that I want to allow any connections into my web socket endpoint regardless of what the origin of that connection is no that's will effectively allow us to do second JavaScript application that will then connect end to this without throwing a cores error so just under this we're never gonna want to try and tackle upgrading this connection to WebSocket connection maybe can do that using the upgrade our dot upgrade and function which is available from the gorilla slash WebSocket package so I want to do WebSocket or error equals upgraded or upgrade just like we said and it's gonna take any response rate err the request and Anila parameter and then because we may get an error here we want to handle that so a fader does not equal no we don't want to say blog dot print line that's error and then we want to say load open mind client successfully connected like so cool so at this point we have successfully been able to upgrade an incoming connection but we aren't listening for on that connection for any new messages and we're not able to send any messages that in that connection so let's first tackle the problem of lessening permanently for incoming messages now I'm going to create a new reader function which will take in that's WebSocket connection and it's gonna kick off a for-loop they'll run forever and then I'm gonna do connection read message which will return message tape P or error and connection dot read message and then again let's handle that error so at fair it does not equal no log doctrine line the error and we want to return in this instance at the resonator and then just below this we want to log dog the line the incoming message like so cool so I want to be able to echo back that message to the client so in order to do that I can use the connection dot rate message function now I can do F error equals connection dot rate message and I can pass in the message tape and the baits and I can see if it's not no then log dot print line that error and return once again cool so coming back into my web socket endpoint I then what to kick off this reader function like so and that should be us good to go so let's try actually run that within the terminal so I'm going to ctrl C my existing server and tape cool run mindo go and I have not passing the WebSocket connection so that solves that let's try to pick off once again and my server has successfully started awesome so know that we assuming we have a working web socket endpoint why don't we go ahead and create a new front-end application that will attempt to connect them to this WebSocket endpoint now I'm going to do this by creating an index dot HTML file and it's gonna have just the basic HTML tags and then I'm going to create a nice bit of JavaScript just at the bottom and within this I'm going to do let socket equals new web socket and it's web socket capital C s I'm gonna pass in the WebSocket protocol / localhost and our service running on 8080 and the WebSocket endpoint has WS like so and I'm gonna say just below that console dot log authentic WebSocket connection and then I'm going to listen in for any sake events so socket dot on open and I'm gonna say console dot log successfully connected and I'm gonna want to send hi from the client message up that socket so socket dot send hi from the client okay I'm also gonna want to define the socket dot on Klaus event listener and that looks something like this so console dot log socket close the connection and I'll just print out the event and I'll say socket thoughts and actually not like that I'm gonna come in here and then I'm gonna the socket dot own error so if we ever get any errors from our socket connection we're going to do error and we're gonna do the console dot log socket error and just simply print it out like so okay so I'm gonna create a new demo here alright say I'll come back into my original one I just split this terminal and now I'm going to use the live server do it module in order to run nest locally on a different port and I'll open up on localhost port five nine four one four and then if I come into my editor or my browser sorry open this up and if I inspect the element three the console I should see that attempting WebSocket connection is printed out and that it has successfully connected now if I come back into my editor I can't see the logs that we claim has successfully connected and I can see the message from that client cool so one final thing I want to do is to add the socket thoughts on message event handler and I'm gonna say message and I'm simply gonna console dot log that's message like so save that live server should then reload my page and if I open up my browser and open up the new live server port open up the console I should see you that the client message - the client has been sent dated my WebSocket connection and been echoed backed by the WebSocket message function within our reader function awesome so unless tutorial we've managed to cover some of the basics of WebSockets and how you can build a simple WebSocket based application in go using the karela slash WebSocket package now hopefully you enjoyed this tutorial and found it useful and I'm hoping it highlighted some of the main benefits of using WebSockets within your own core applications now if you don't enjoy this you may like my tutorial series which utilizes WebSockets to build a real-time chat application using post react and cool now it covers things like how you would pull WebSocket connections and do things such as broadcast updates to all connected clients now I'll leave a link to that and the description below if you did indeed like this video then please leave a like and if you think I could do anything better or if you think I've messed anything or have any suggestions then please let me know in the comment section below and as always please subscribe to my channel for more programming content Cheers
Info
Channel: TutorialEdge
Views: 33,781
Rating: 4.9101796 out of 5
Keywords: programming, tutorials, coding tutorials, tutorialedge, go websocket tutorial, go gorilla/websocket tutorial, go basic websocket tutorial, go realtime websocket tutorial
Id: dniVs0xKYKk
Channel Id: undefined
Length: 13min 45sec (825 seconds)
Published: Sun Mar 17 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.