How to Use WebSockets in Unreal Engine

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

But Unreal has only a websocket client right? I have been thinking about creating a small websocket server for Unreal for the last few days. So that you can send data back and forth via HTML websockets to Unreal.

👍︎︎ 2 👤︎︎ u/Socke81 📅︎︎ Nov 19 2021 🗫︎ replies
Captions
[Music] hello everyone in this video we will be going over how to open send and receive messages over and close a websocket connection between an unreal engine client and any server application for those who don't know websocket is a full duplex bi-directional communication protocol that enables real-time data transfer from and to the server unlike in http with websockets a new tcp connection does not have to be initiated every time the client wants to exchange data with the server and vice versa once a websocket connection is established either the client or the server can pass data to the other at any time the connection is still open for instance in this demo none of these clients are connected to an unreal engine dedicated server they are all running on separate standalone processes yet the clients are still able to communicate with each other via a basic node.js server and that same server is able to communicate with all of its connected clients on its own volition if any of this sounds confusing then don't worry everything should make more sense as we progress throughout the tutorial this tutorial can also be great to learn from for people who don't have a ton of coding experience another amazing tool that can be used without much coding experience is our sponsor of today's video core core is a new pc gaming platform that anyone can create share and play pc multiplayer game it is completely free and available for download on the epic game store as we said you do not need coding experience it is powered by unreal engine has built-in multiplayer and can publish your game instantly for others to play with access to thousands of free music sound and art assets you can quickly build games from scratch you can also use lua or scripting games if you do know how to code you can get a 50 revenue share to the core perks program and some core creators have been able to pay their bills buy their dream cars and even quit their day jobs with the help of the perks program core is also hosting the game creator challenge with thirteen thousand dollars in total pricing they are collaborating with eight popular youtubers to lead a faction of game creators to compete in the same challenge you can join your favorite youtuber you want to support and be part of that faction submit your own games made in core and win up to a thousand dollars in prizes the deadline is december 15th and you can use the link in the description to learn more about the event core is a great service to use if you are just starting out your game development journey it sure was for us check the game jam page in the description below for more information along with the link to download core and go make your best game yet so the first thing we are going to do is open up the unreal engine editor specifically the project browser because once that's open i'm going to create a new project using the third person template and in this video we will be working with a c plus plus project since the websockets module in unreal engine at the time of filming this video is not exposed to blueprints natively however the c plus plus code is pretty straightforward and easy to convert to blueprints with that said let's name the project whatever we want and click create once the project has been created the very first thing that we have to do is go to our projects build.cs file and in there we have to add the websockets module to our projects list of public dependency modules so that we can later access code from that module in our project after that's done go ahead and build the project now let's open up our project in the unreal engine editor because we are going to create a new class and that class is going to be where the websocket client configuration is going to be handled so let's create a new c plus class and from all the parent classes we can choose from for our new class select the game instance class i'm going to name the class after my project and then click create class now you don't necessarily always have to use this class for websocket related functionality i only chose the game instance class because it is a persistent actor that exists throughout the running life span of a game so when you're connecting to or disconnecting from a server the game instance will not be destroyed or recreated therefore in this sample project a websocket connection can theoretically stay alive for as long as the game application is running for until it quits which may or may not be what you want but in a lot of scenarios this is useful especially for non-gameplay related features that you want to be available for someone regardless of whether someone is currently playing in a game session or standing by in the main menu for example chatting with friends who aren't in your game session or getting a live notification about a party invite from one of your friends but moving on once our game instance subclass has been created inside the game instance header file i want to include the i websocket header file because i want to have a public member variable in this class that points to the websocket instance that unreal engine will use to communicate with a websocket server that variable will be of type t share pointer with a template argument of iweb socket and it will be called web socket now building off that earlier idea of having an open websocket connection from the beginning until the end of a game instance's existence let's override the function that gets called when the game instant spawns which is called init and the function that gets called when the game instant shuts down which is called shut down after we have declared these functions let's go to the game instance c plus file and actually define them by typing out the return type class name double colon method name parentheses squiggly brackets and we can just copy and paste this for the shutdown method then change the name and since these methods are overrating functions in the u game instance parent class we should call those inherited functions within these child implementations so that the base logic still gets executed whenever these functions get invoked before we add some custom logic to these method bodies we need to include up here the web sockets module because that module will be used to create a websocket object which will be done in the init method however we have to first check if the module is loaded by calling the f module manager is module loaded function because in packaged unreal engine games i have noticed that the websockets module is not loaded by default so in that case we can load the module using the f module manager load module function after we've ensured that the module is loaded we can now use the f web sockets module singleton to create a new websocket and pass in the url to which the websocket server will respond very soon in this video we will be running a simple web socket server on localhost on port 8080 now that we have a websocket object let's create a client connection to the server when the game starts by calling the websocket connect method and let's close the client connection to the server when the game ends if there is even still a connection at this point by calling the websocket close function once that's done go ahead and compile your project in order to test our newly compiled changes we have to do a couple of things before we can run the game in the editor first we have to make sure that our project is using the new game instance class that we just made so to do that go to the project settings specifically the maps and mode section and change the game instance class to our custom class second we need a websocket server to actually connect to so for the purposes of this video i have prepared ahead of time a simple websocket server written in node.js that we are going to download off github and run so i would recommend that if you don't have git or node installed to pause the video and install what you don't have links to these pages will be in the description below once you have confirmed that you have git and node installed on your computer copy the github repo link open up command prompt or any command line interpreter and cd it to wherever you want to place its javascript project in and in there just clone the git repository after that cd into the directory containing the repo it should be named after the repo and install the necessary node modules that the server code relies on and finally we can run the sample websocket server just to note all the commands used in this video will be in the description below while the server is running in the background listening on port 8080 we can play our game in the editor and if we go back to command prompt you will notice some new log statements that show that the game has connected to the websocket server and if we go back to the editor and stop playing the game there will be log statements in command prompt that show that the game has disconnected from the websocket server and in this video we are not going to do a deep dive into the node.js server code therefore throughout the video we will only be examining the server from a black box perspective because this video is primarily about the unreal engine websocket client interface but if you do want more information about the server used in this video i would recommend going through and reading the server code since it's very self-explanatory and if you have any questions about anything during the tutorial feel free to comment down below moving on let's quit the server and go back to our project code so now we are going to set up the event handlers on the websocket interface in order to respond to specific events that occur with regards to the connection between our unreal engine client and the whatever server you are communicating with so that we know that those events are actually happening for example in that quick little demo we had the check command prompt to verify that there is a connection established but we can also verify that on the unreal side by adding a lambda function to the web sockets on connected event and whatever logic is in this lam the function gets executed upon connecting to the server and so in that case let's just add a debug message on the screen that lasts 15 seconds colored green and says successfully connected but how will we know if the connection failed to create well there's an event for that too it's called on connection error and it will send us a error message in that case let's do the same thing as before show a debug message but make it red and instead of saying successfully connected just say whatever the error says but what if a connection was created successfully but it got closed abruptly while we were playing the game perhaps by the server internet connection etc well there's an event for that too called on close that'll send us a status code a reason and whether or not the close was clean and we'll do the same thing show a debug message except make it green if it was a clean close otherwise red and have it say connection closed plus the reason it closed and then of course what if the client receives a message from the server while they are connected the event for that is called on message which takes in the message string sent to the client by the server and in the function same thing except we'll make this debug message cyan colored that says received message plus whatever the message was note that this event is only for string messages for binary messages there is a separate event handler called on raw message and lastly there's an event for when we the client send the message to the server and that event is called on message sent and we'll make this debug message yellow that says sent message and then whatever the message was after that let's build the project and now let's test the project against our node.js server again so first let's run the server then play the game in unreal and notice that we see a couple of debug messages the first one says that we have successfully connected and the second one says the message that we got from the server if you're wondering what that string of random characters is the server randomly assigns a unique identifier to each connected client so that we can distinguish between the unreal clients which will be better exemplified later in the video also you'll see more debug messages as the server on its own sends a message every 15 seconds to all the connected clients that says how many connected clients there currently are to test the on closed event handler let's quit the server without quitting the game and to test the on connection error event handler let's restart the game without restarting the server but now how do we test the last event that we implemented on message sent for that we need to write some logic to actually send data from our game to the server so for this tutorial i think the simplest way to do this is to set up an event that responds to player input so in our project settings specifically the input section let's create a new action mapping call it whatever you want i'm going to call it notify server and give it a hardware input value i'm going to give it the e key now let's write a new function that'll get fired off upon the client pressing the e key in this case i'm going to declare this function in my project's character class and name it after what i named that new action mapping then i'm gonna define the function in the c plus plus file return type void name of the class double colon name of the function parentheses and squiggly brackets and like we alluded to earlier we want this function to send the message across the websocket connection to the server that's why we kept a public reference to the websocket object in the game instance since we can access the game instance from our character so let's include our custom game instance header file and then moving back down to the notify server function let's get a pointer to our custom game instance by casting the result of get game instance to our custom game instance class next let's do a customary null pointer check on that game instance and then check if there is currently a websocket connection using the websocket is connected method if there is then let's send a message to the websocket server using the websocket send method and i'm going to make the message based off the action mapping keep in mind the message can be anything for binary messages you would use a different version of the send function after finishing the notify server function let's bind it to the action mapping by going down to the setup player input component function and adding another call to bind action with the first parameter being the name of the new action mapping and the last parameter being our new function once that's done let's build the project one last time hopefully as we finish the code writing portion of the tutorial and while we wait i just want to give you guys some things to ponder especially for those who are interested in blueprints this notify server function can be modified to be a u function with a blueprint callable specifier in fact any of the websocket c plus plus code that we have added can be wrapped in a blueprint callable view function we're not going to do that in this video but just wanted to mention how one would go about doing websocket related things in blueprints once the build is done let's test our game again by running the server then our game and press the e key or whatever hardware input value you used for the action mapping you will see from the debug messages as well as from the server logs that we were able to send a message to the server which responded by sending the message back to all the connected clients now if you want to test with multiple clients in the editor then be sure to modify the advanced play settings to turn off the run under one process setting otherwise each client will display the same debug message and it will be almost impossible to keep track of however for the rest of the video i won't be testing in the editor rather i'm going to package the project to better demo how the client server interaction works and prove that the websockets module works fine in package games so if you're on unreal engine 5 like me i'm going to turn off lumen as well as virtual shadow maps really quickly for performance reasons then right after i'm going to package the project for windows since that's the platform that i'm on and this is optional but i just like to personally keep packaged builds in a separate folder once the project has finished packaging let's run the server as well as a few clients for this showcase i will be running each of the clients in windowed mode all on the same screen with the use of the windows and arrow keys and as we can see when one of the clients presses the e key the server gets a message from that client and broadcasts it to all the connected client and since each client gets a unique id from the server we can distinguish which client pressed the e key and as seen before already the server is telling the connected clients how many of them there are on a 15 second interval congratulations though you have successfully integrated the websockets module in an unreal engine project to end the video i'll leave you guys with some more food for thought the use cases of websockets go beyond this example for example instead of clients telling each other that they pressed a key in real time clients can exchange with each other chat messages or game invites through a websocket server in real time and the variety of possibilities doesn't just stop at the client the server can also be customized customized to do so many things in addition to telling clients how many players are currently online for example it can watch for the status of a matchmaking request and let the client who's queued up know when they've successfully gotten into a lobby and that is all for this video thank you for watching if you enjoyed the video then please like comment and subscribe join our discord server follow us on our other social media consider donating the flop ram special thanks to our higher tier patrons and michael camiso graeme devine james trabone logicalcuber dwight everhart mark wetch jimmy wescott morgan heinemann elise bioblaze payne lucas moscon and rick morgan you guys are the main reasons that we keep pushing out educational content on youtube for free and also thanks to core for sponsoring this video you can use the link in the description to download core for free everyone have a fantastic day [Music]
Info
Channel: Flopperam
Views: 1,040
Rating: undefined out of 5
Keywords: ue5, ue4, unreal engine, websocket, web sockets, client server data exchange communication, unreal engine client nodejs server, dedicated server, listen server, game development tutorial, chat messages, party game invites, queueing up lobby notifications, realtime live data feed, multiplayer game dev, c++ blueprints, git, nodejs, core games, manticore, game instance, character input event
Id: l9TTmtDBTWY
Channel Id: undefined
Length: 21min 25sec (1285 seconds)
Published: Fri Nov 19 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.