Making Reactjs real time with WebSockets

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
okay so today I will give a talk on WebSockets anybody using WebSockets on the application I'm good oh yeah if I do anything wrong to give me some insider tips there please and talking about how to integrate with the web side clip excellent that was actually pretty simple I'm just kind of give overview of how you can add them to react yes um one thing is with any react app is you have typically a server dependency right you've gotta talk to some API it's most common api's are going to be rest graph QL we did talk while back on that there's several others with the most common is give your best I supplied that order I am hiring take a link so rat I think it really addresses transactional requests you make the request you wait for response to get your response so but the thing with the world it works in real time right so that's where WebSockets come into play if you need to get real-time communication from server a common method that used to do in the back a while ago with a long polling with browsers that are incompatible with WebSockets you still do long polling where you just kind of keep this open HTTP connection the WebSockets have come in to replace that so they're really useful for real time applications like internet seeing monitoring systems collaboration systems in games stock market ticker info where it's got rich data to the client job applications radio play lifters you can go on about real time applications so how does a web socket work so basically it's still over HTTP you make just an initial call back to the server to do this handshake you're going to upgrade say I want to use a WebSocket connection you still do it over for 80 or 443 you can do other Forks but recommended still 80 or 443 supports SSL at that point you have a connection open and it's just a socket connection messages came back and forth there's no request response just whoever wants talks to talk on the wire from the client to that server Angele one of the site closes that connection whether it's the server or the client it's ours browser support for interesting the stance that like any browser that's secure it's going to support it right so a lot of the older browsers don't support they're not secure so you shouldn't be using in many ways but all the newer browsers do support web socket so it's free safe assumption to to do that there are frameworks out there flying framework that do provide fallback I believe that some of them I think just may provide a fallback if it can't make that website and actually give using their server and their client together but even so I think some of those things are being deprecated and we've got those frameworks make it smaller so common ones that are out there today are WS socket IO Satya there's a few others and may even be based off other frameworks like engine io is what Sakai OS based off of and I think Spain's we're top jeaious is based off the thieves kind of higher-level frameworks encapsulate that lower level of communication to really have gender stamps going on and how to make or establish that connection because they just extract all the WebSocket days that you have to work for this demo I'm going to use doc - last when later why actually choose melons but they're really I don't have a preference they all seem to work does anybody have a preference on which ones they use no just really all kind of work so it's going to get started with the demo go ahead okay so just to a brand new map and so I'm going to right here is a chat client call chat client who out here is use for a track that pretty cool like super simple to create app real quick so let's let that run so if I go ahead and jump into that trip through what I call it just fine just fine when I use your quick yarn start circa okay it's running so this is basic boilerplate that they give you so the first thing we need to do when we write a chat client is have some kind of user input so when you start the server one more time so from the app we find between the input box right so we'll just throw that out there let's go to so source and then after F is where our our main application is the main component but I'm going to create a chat component to run it over that will call that components and we'll call this chat so I need a new components and call that chat so doesn't really have any yet the Wilmington text box in there right so that would be an input type text and then a button right that would be enough to give me I did that right I just I signed on that but we have my rank what's up oh yes I gotta add it back yeah absolutely so yeah import that I chose rectifying import chat from and so we have a chat box so not very pretty but we can do that who strap around the whole thing and then let's throw bootstrap in our index there cooks ok so now we have a nice little format set box it's not doing anything yet so now comes where we went to server communication right so we could choose like a red service that we're going to do WebSocket here and so one things with WebSockets is it really is no contract so you kinda have to define that on your own in this case my chat so we're just going to echo everything that I send it and just like over back down to the clients so first thing we want to do is connect the Fox client API so we'll bring in socket and then we're still in the constructor for now so what we can do actually if I go out and talk about that real quick so what it's locked is so to implement that case is really simple so we won't do we won't import it this way we'll just use the NPM package but this is route all the food you need to communicate with that server socket that's it what was it doing by creating a new sock object that's going to go ahead and establish that connection and then you can subscribe to that with your function and once that connection is successful it will call this an open function in this example if criminals commute and send a message to the server dad and then any additional any messages will come down from the server that get pushed it's going to call this on message function you can subscribe to and then you can do whatever you want with it in this case they close the connection which within cause the close function to get called so we take that same logic we can just put that out here and so I already have a server that's running so it's Jeff server and so do the same thing when that connection is open I'm not going to send the message I'm just going to throw in the console that connections don't think any messages get pushed from the server to the client which is right now just a console log and then if that connection happens to close we'll just put that in the console key and for this is a simple sake of this demo I'm just going to stick that into a state and we also want to add to our state messages so that we can kind of queue up those messages any kind of server as us a message we'll just go it into this array and then we can use that to render and I'm displaying on our chat line so let's see what that looks like okay that really won't look like anything yet because even though I have this form out there there's nothing wired after that button so click on it I can give any so let's just fire up that button so I'm for one swift submission or just wire that up real quick the surf instructor up here and then so what's going on here so as soon as I click scandal form submit I'm just gonna prevent default of the page returned zeroed on me and then I'll grab a message deck and just send that up to the server using this object that I'm passing in state those basics and we go toss that in here Becca so now I can type in a message and we see can opened to the server so if I send it it sent it up and then it server just simply equity back down so I'm actually getting a message back from the server so it's pretty simple right like it's pretty simple to add a sock that app pops like morning I can take care that real quick okay we're giving actions which is an object now we're all forgetting that this is just a array it gets rid of that so now what we want to do is now we've got that message we want to render another page so we'll just end that add that for a rendering that's pretty simple we'll go into our render function on the chat we'll just throw in pul some time you think bootstrap I can just say list fruit so messages is the pat-down in tonight's this is a property problem so let's just grab that our props and that's all being handled basically what happens actually it's not being handled when that message convene we need to push that message into state so that it can be packed into that component so we are incoming soft messages so basically what happen there is message will community top comes off easy data if our event and we'll just push that into eight so in the chat client we now need to read that from the prop so what are we doing there so we're looking at the prop we're going to map over that messages and throw that into an ally and then anytime you have a map function that what the key in there so we have a counter just to throw a unique key on there okay yes so that method I can store real quick suspense else because I just referenced it here since it since I have another function I can't reference this because of scope so I'll just play with so so now what happens if i type in send it a I get a response back cool so this really working you guys trust me that it's working I guys probably not so will it test this end one of the cool things about create react app is I can just push this to get head pages so let's go ahead and do that fine gh-pages so let's see that we click the what happens when I created adapt I get this big long read me so let's just search th places and it tells you if you follow these instructions you can deploy that to a cadet pages so first thing is yarn add we did that next thing is add two scripts to my package.json so let's do that so with the pre deploy deploy so basically free deploy just going to run the build compile it and then transpile it and then chase pages will actually push it up to yeah so let's go out to get up creating your repos and we'll call check and we can just run this command so get in it I don't need to read me you can implement I won't worry or commit right now not necessary so we do need to add the origin and then the last we make all this work is in your package JSON you have to define what the home page is going to be and so my home page will be chat client which is the name of my github project and then we folks okay I've got iOS kind of standard to the pages to graph so with all that done I should be able to NPM run deploy yes I think I killed my notes this morning so I again okay publish so let's go out again and for you refresh check code out there we do suite so let's just check that off a Depot so I could have done 94 let's do so okay cool okay okay so who else wants to go to the page and type in a message let's see if it works you control me there it is hi pal hey it's working we now check hi I can check back in pretty cool huh up for you so it's not that simple a couple things I will note doubling down though one is if you look my package.json I actually don't have a reference to sock jfif okay fine I said it was a reason I chose it for this demo and the reason is create react app actually ships with the client as a good foods going to probably go back and actually say yarn at joy that's fine you could probably do something too just so you know that you're actually going to be using this the party or project but I'll add it ineffective so I found that out the an accident like that I thought that was what would like broken and then it wasn't what was broken to those already there okay so let's in their app working but the reality is there's a lot of times where this code right one is this isn't too bad here because it's it's not using a station but you know I'm using state year and I like to write stateless components the other thing is I'm actually putting my hit client into safe that's probably not good either that's not a good good thing to do so what else would we do well we could choose Redux boa and then we have global space and then we want to have a TMI component I can subscribe to use the reader subscribe to subscribe to event and then manipulate my thoughts my soccer clients that way so let's try that let's do that the first thing is to add a couple more holders we want you to action we need our reducers unless that was actually reducers and I explain what they are doing okay so for for this simple client all I really doing fractions are sending or receiving so probably if I were to make it a little more robust I would add other actions for actually connecting to the server detecting from sir one of the big things about socket client is if you lose that connection the client has to reconnect and you have to keep track of that I'm not going to do that into that I'm just gonna worry about sending and receiving and if you lose connection at the refresh your browser so I went into stuff or even if such aspects action types into the action file down a process to create an action type file and just stick them all in there because you don't have to be small enough app so I think there's small out that I don't ask and then let's add our reducers so what we're actually actually doing to the state so let's do a new file account the how in the way so for reducers we'll import those action types the receive message and send message because I'm actually many pollutants data I might have an initial state so a couple things that I'm actually doing that's probably a little weird for Redux is actually passing my action through I'll explain as to why I doing that when I get there but it's mostly because I need to know whether I'm sending or receiving from the server on that action when I have my subscribe I'm just gonna pass it all the way through so that's what you're seeing on so I'm putting action into my state's going to be my last actions really what's going to be and then I mean if the message comes in to receive message I'm going to push the message into my face and if it sends message action that came through I'm not really gonna do anything that they don't just change saying hey the client I trying to send a message so that's those in there the next thing is actually free to reject store so let's do that in Mariza store in my index jf so this creates a Redux tour actually guess I still needs a wrap-up provider though to add my store around app so these all boilerplate goodness you're writing a reject a few just have that in there you're importing your provider create store combined reducers and then you actually combine the reducers I only have one reducer guys I need to combine it but have it and then update my render function so originally the render function uses rap app with a provider it's just app you will need to register a listener so this is where why I have two actions roof check so this code here I'm going to call Thor doc described which is just a function is available in redux on my floor maybe it's off and I'm going to grab when any actions problem mattering actually was send or receive this always gets called and that's why I'm Pat I need an action so that I know which action was being called so I'm gonna grab my page I'm actually just gonna grab messages from state in that state I have this action object and then inside that I'm just going to type so my type coded offend mrs. or receive message mid case if the user clicked a button that cause an action is dispatched and that button they clicked is going to create send message so if that happens I have my switch statement says okay when they click that button let's send the message to the server so I don't have any reference the sock in here because sock is still inside my actual component so it's going to rip all that stuff out of the component that components here so I no longer need to have this here it's just makes it's been completely stateless actually means construct it off so it's just a state component again which is not there we're gonna pass across in so we have certainly reference the socks and wear so I'm just a stick that into my index code where my store is located do that and then to the same exact code that was in a component let's just add it back into here so we're going to say socks and so it's the exact same thing on open connection with some console log on message it's gonna pop the log and then close the difference was when the message came in we pushed that in a fish to state instead of doing that now in redux you have to dispatch so let's go ahead and dispatch and so we'll just call our store a read X for which we defined right here by calling create store and then asking in that reducer and so that reducer has action called receive so let's take a look at a reducer quick action actually ties for the action so the result which then passes with to the resource so they're actually keys which is a type of receive messages and go through our reducer receive mess and that's where we actually push the text back up data oh okay that that's it for this now this is a now a stateless component but I'm a finance reference props where props come from I got to get frost from Redux so and you guess fi having this function adding a function called map state the props that does all the magic for you there and then I'm also going to bind my action readers so the state's going to be fed into my component from read us and I'm going to around make it a property prophet messages just grab a trail either and the one last thing is change out this I can have to use redux connect to export now this is a standard boilerplate redux clinic and a clique called a stone Rochester this is here but I want this version of it so did that's a clear real quick stuff on there all kinds of stuff oh you're trying to script X fun my apps not ready let's start the app real quick again and see if it's working so the server didn't curse I cannot resolve reactive attacks yes so I went through all this code metal thin but I never added it to my packages yarn and let's add Redux and we need X 3 X redux you know the answer it's connection open okay cool anybody still on the page send a message let's see if it's working with Rita we're getting message recompose all things yes cool apps working I could push this back up to get up I'll push all the code up later so any questions on the client yes yes if I did then I would have to bring me a sock JX into my reducer so and if I was we thought let's go a little bit more I would take this and put it on you chill class and then dysfunction also this entire thing should go into probably that class by you till class and I would pass in something like when I do Z to say I did had to think all you know custom client or whatever I was that from an address and then test in my dispatcher it kind of II couple that and then that function that has the dispatch get in feed all the way through but Simon does anybody three-side with the server code look like bring that up the server code literally was just copied straight from the Sox Jeff server side Sox right here that splitter of the server code that I used the only thing is I I just passed this was undefined I didn't need to this is like fall back hoe so if the server browser doesn't support talk to this it can be via JavaScript back down to the client to give backward compatibility like for one polling that's what that's doing but I don't care for older browsers but basically it's just very similar has this you create this object and then you support on connection and then in my case I'm listening on port 443 and you have this new file hammerstone that's my path I think I change my path and flash a chat so that's what this is here so whatever path are you assign so yeah that's that's the server the only other thing I did I added code to this was this is only going to echo back on the exact connection that came in so I added a on the on I'm actually taking vidcon object and I just have a an array I'm just pushing this arrey and then he's conned out right I'm actually doing a for-loop just taking all connections and just spamming it out to every connection the same so I'm doing dot right on those that way it could hit all the clients that are listening so some considerations when using these aren't the only considerations is just some things like hada is by default they only support text and binary messages so you know from the Bill send JSON objects if you would like the normal rest which you have to do is stringify them send them up and then the client the server when they send this send it back down and stringify you gotta park so there's potential overhead that your string flying and parsing writing you can actually map free books and even if do all your validations that can have to write that there's no caching or compression built in the socket it's just messages coming back and forth so you could because you can do binary you could if you have really large objects you could compress it I guess on the server side and pinned it down and use some kind of JavaScript decompression framework this is just may not come in the order that you expect them coming year and try to keep in check out of your connection to open and close it if you lose connection you have to reopen it so the most recommendation thing is you know store that Sh you'll get an alert you know connections are close you gotta tell state dispatch okay it's closed so I open it and do whatever you want there and browser compatibility is also another consideration other any other gotchas or pro tips with WebSockets you think if you're going to but this is ones icon I ran into when I was okay and they're gone that's another another good gotcha yeah so it's it's real time right here you're not really looking to what's going on right now as a message you're getting in so yeah any questions well thanks
Info
Channel: Phoenix ReactJS
Views: 40,341
Rating: 4.7632399 out of 5
Keywords: react, reactjs, redux, websockets, create-react-app, sockjs, sockjs-client, coding
Id: 82GDkSFmEJc
Channel Id: undefined
Length: 39min 17sec (2357 seconds)
Published: Thu Aug 10 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.