Connecting Unity Clients to a Dedicated Server | C# Networking Tutorial - Part 1

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys my name is Tom and welcome to the first part of my c-sharp networking tutorial series in this video we'll be setting up a TCP connection between clients and a dedicated server I'll be building the client in unity and the server will be a basic console app I learned a lot about multiplayer games from Kevin Kai Mac whose channel I'll link to down below some of the core parts of the networking solution will be building in this series remain unchanged from what he taught on his channel but over the last two years I've modified a lot of things to make it what is in my opinion much easier to work with as a developer I've also added UDP support which I'll cover in a future video if at any point you run into issues make sure to join my discord server where you can ask for help there's an invite link in the description we'll start by setting up the server so open up visual studio and create a new project choose the c-sharp console app template give it a name and choose a save location I'll call mine game server but you can obviously name it whatever you like you'll notice that if we run the project right now it opens a console window which immediately closes again for now we'll fix this by simply adding console.readkey at the bottom here now the window stays open until a key is pressed we'll also quickly rename the console by setting its title property to a string of your choosing once again I'll call it game server we'll need a place to house all the server logic in so create a class called server at the top add the system net and system net sockets namespaces in the server class we'll need a public static int called max players I'll make this a property which can only be set from within this class do the same for the port property and then add a public static TCP listener field next we'll add a public static method called start inside which will do all of the necessary setup for the server make sure to give it two parameters one for the max players and one for the port number inside we'll assign the parameter values to their respective properties and then we need to initialize the TCP listener will pass IP address dot any as the IP and you guessed it our port number for the port then we'll call the TCP listeners start method followed by its begin accept TCP client method for this one we'll pass it an async callback called TCP connect callback and null for the object state the error that pops up now is because of the callback method we gave it doesn't exist yet we'll create that in a moment before we do let's add a console dot write line at the end here to let us know that the server started successfully I'm also going to write starting server to the console up here although that isn't really necessary now we'll come down here and create a private static void called TCP connect callback and this will take in an i async result in here we'll create a local variable to store the tcp client instance returned by the tcp listeners and accept tcp client method to which will pass our async result once a client connects we want to make sure to continue listening for connections so we'll call the tcp listeners begin accept tcp client method again passing it the same values as before at this point we need a more permanent way to store client information so let's create a new class and call it client once again make sure to add the system done net and system net dot sockets namespaces at the top inside the client class we need to store the clients ID and a reference to its tcp class which doesn't exist yet below create a public class called tcp and give it a public tcp client field this is what will store the instance that we get in the server's connect callback we'll also want the clients ID in here but we can make this field private as well as read-only to assign the ID field will use a constructor which takes in an int then we'll add a public connect method which will take in a TCP client instance before I forget let's give the client class a constructor as well inside which will assign the clients ID and initialize its tcp instance back down in the connect method we'll assign the tcp client that's passed in to the soccer field create a static data buffer size field which will set to be 4096 bytes or 4 megabytes then we'll assign this value to the sockets send and receive buffer sizes will also need a private network stream reference and a private byte array so create those and then set them in the connect method I misspelled received so quickly fix that if you did as well finally call our streams begin read method will pass in our receive buffer an offset of zero data buffer size as the size received call back as the callback and null is the object state I'll be placing to do comments throughout the code feel free to omit these as their sole purpose is to make sure that I don't forget anything important in future videos now we need to create the private received callback method which will take in an i async result in here we'll put everything inside a try/catch block so that any errors don't cause a server crash in the catch will simply write the exception to the console and in a future video will properly disconnect the client in order to receive data we need to call the streams and read method which returns an int representing the number of bytes we read from the stream will store this in a variable called byte length before we do anything else we need to check if the byte length is less than or equal to zero in which case we'll want to simply return out of the method if we have in fact received data we'll create a new array with a length of byte length and then we'll copy the received bytes into this new array after that we need to handle the data but we won't be doing that today instead simply call streamed up begin read again with the same parameters as in our connect method to continue reading data from the stream that's it for the client class at least for now now that we have a way of storing clients let's add a dictionary to track them back in our server class will use the clients IDs as keys we need to make sure to fill this dictionary so let's create a private static void initialized server data method at the bottom in here we'll use a loop to populate our clients dictionary starting with 1 is the first ID not 0 back in the TCP connect callback method we need to assign our newly connected client to an ID so we'll set up another loop once again starting at 1 make sure to change the condition from less than to less than or equal to which I forgot to do an initialize server data inside the loop we'll check if that client instance as TCP socket is null and if it is that means this slot is empty in which case we'll call its connect method passing in our newly connected TCP client instance we'll also return out of the method to make sure the new client only takes up one open slot if this loop executes to completion that means the server is full so we'll print out a message to the console before the loop we'll also put a console dot write line which will print out the connecting client scipy import don't forget to call initialize server data in our start method back in the program classes main method we can finally start the server by calling server dot start and passing in a value for the max players in which port we want to listen on during development you can use whatever port you like however if you plan to release your game I recommend choosing an unused port from this Wikipedia list I'll leave a link in the description lastly run the server to see if everything works and make sure to allow it through your firewall otherwise clients won't be able to connect that's it for the server now let's move on to the client startup unity create a new project and choose a save location and name I'll call mine game client will start by renaming the default scene to main and creating a scripts folder inside will create two scripts one called client and the other called UI manager open up the client script delete everything inside and out of the system net and system net dot sockets namespaces at the top we'll use a singleton implementation on the client so we'll need a public static client field called instance just like on the server we need a field to store our data buffer size so add that as well we also need a field for the server IP set that to 127.0.0.1 which is the IP for localhost as for the port set that to whichever port number you chose when setting up the server finally we'll need a field for the local clients ID and a reference to its TCP class will use unities awake method to initialize our singleton first we need to check if instance is null in which case we'll set it to this instance of the client class if instead instance already has a value and it isn't this instance of the client class will destroy this instance that may be a little confusing but basically it will ensure that only one instance of the client class ever exists in unity start method we'll create a new instance of TCP and assign it to our TCP field then we'll create a public connect to server' method we'll add code to this shortly similarly to the server we need a TCP class with references to our TCP client instance and its network stream as well as the byte array field we'll also create a connect method inside which will initialize the TCP client and its send and receive buffer sizes finally we'll initialize our receive buffer and called rockets begin connect method passing in the server IP and port connect callback and the TCP client reference now we'll create the connect callback method which takes in an I a single result inside will call the TCP clients and connect method will check if we are in fact connected and if we are will assign a value to the stream field and we'll call the begin read method just like its counterpart on the server will pass in the receive buffer and offset of zero data buffer size as the size a receive callback method and null as the state will make that method private and it will take an eye async result as a parameter since the contents of the try block are identical to the servers we can simply copy and paste that over next we'll open up the UI manager script delete everything inside and add the unity engine the UI namespace at the top create a public static UI manager field called instance as well as a game object reference called start menu and an input field reference called user name field since we're using the same singleton implementation we can copy-paste the clients awake method to the UI manager will also add a public connection server method which will be called when the player clicks the connect button once that's clicked we want to hide the start menu disable interaction with our user name input field and we want to call the clients connect to server method inside method will call TCP connect make sure to save all that and then return back to unity in the editor add an empty game object to the scene call it Client Manager and attach our client script to it next create a canvas call add menu change its UI scale mode to scale with screen size and set the reference resolution to 1920 by 1080 add a panel object to the canvas and call it start attach the UI manager script to the canvas and assign the panel to the Start menu field next we'll add a button with a width of 300 a height of 60 and a vertical offset of negative 40 change its text to say connect and set its font size to 50 lastly we'll add an on click event and choose the UI managers connect to server' method now we'll create an input field with the same dimensions as the button but with a vertical offset of positive 40 this time set the placeholders in the text font size to 40 and change the placeholder to say user name instead of enter text finally assign the input field to the UI managers user name field hit play and start up the server once the server is running hit the connect button and you should see the connection message written to the console if so congratulations you've successfully setup a connection between your server and your client if not double check you didn't miss anything and if you're really stumped feel free to join my discord server and ask for help the link is down below that's it for this tutorial if you enjoyed it and found this helpful don't forget to smash the like button in the next part of this series we'll start sending data back and forth between clients in the server so make sure to subscribe and hit the notification Bell so you're always notified when I upload another video thank you for watching and I'll see you again next time [Music] [Music] you
Info
Channel: Tom Weiland
Views: 434,367
Rating: undefined out of 5
Keywords: unity networking tutorial, unity networking tutorial 2020, unity multiplayer, unity multiplayer tutorial, dedicated game server, unity multiplayer server, c# multiplayer tutorial, unity client server, c# networking tutorial, unity multiplayer game development, how to make a multiplayer game in unity
Id: uh8XaC0Y5MA
Channel Id: undefined
Length: 12min 29sec (749 seconds)
Published: Sun Oct 27 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.