Networking Basics
There are two realms in networking on S&box. The client, and the server:
Client: Each person playing in your game.
Server: The process that is responsible for orchestrating your game with all of the clients in it.
By default, both sides will know nothing about each other. But networking allows either side to communicate and keep each other in sync. While the same code will be run on both the client and server. No variables and state information you make are shared between them. Due to this, all variables you create whether they are created the exact same way or not will become out of sync when something is done on only one realm. This is where networking comes in. This allows you to share information between both the client and the server.
Example
Upon a client joining you will find the above in your console. Notice how they are not the same.
"But why?"
The ClientJoined
method is only called on the server. Because of this, only the server adds one to the NumClients
field. Since this integer is not networked the clients will never get an up-to-date NumClients
field.
"How can I fix this?"
With a small edit to the code like so:
Now when a client joins you will find the above in your console.
"What changed?"
Three things were changed:
- The
partial
keyword was added to the class. The S&box code generator will attach more code to the class in a separate file to support networking types and sopartial
is required for the code to compile. - The field was turned into a property. This is because S&box networking cannot work with fields. It requires a property. (What's the difference?)
- The
Net
attribute was applied to theNumClients
property. This is to mark the property for networking.
"What is the catch?"
- Not all classes are capable of networking. Only
Entity
,EntityComponent
,BaseNetworkable
classes, and anything derived from those are networking capable. - Not all types can be networked, see this list for available types.
- Properties marked with the
Net
attribute cannot be edited by the client. It will not produce an error, just nothing will happen. If you have code that requires updating on the client side then you need prediction.
"How will I know when my property gets updated?"
You can add the Change
attribute to your networked property and it will call On[Property]Changed on your class on the client side.
You can read the dedicated page for network callbacks here