Saturday, 1 February 2020

The Client<-->Server Division [1.14.4+]

The Minecraft code is divided into two “sides” – Client and Server.
  • The Server side is responsible for maintaining the master copy of the world - updating the blocks and entities based on packets received from the client, and sending updated information to all the clients.
  • The Client side is primarily responsible for reading input from the player and for rendering the screen.
There is one server, and a number of clients which connect to it. Even in single player mode running on a single computer, the server and client code are running simultaneously (in separate threads).

Some parts of the code are used by both Client and Server code, for example Block methods which describe the behaviour of Blocks and which are needed on both sides.
Vanilla groups these three types of classes into "client", "server", and everything else ("common").

If you are writing code which might be called by either Client or Server, how can you tell which side has called the code?
Your method will nearly always be provided with a World object, or with an object containing a World field (typically called world).  If so:
  • if world.isRemote is true, this is Client side
  • if world.isRemote is false, this is Server side.
As a last resort:
  • EffectiveSide.get() returns Side.SERVER or Side.CLIENT.  However it is not robust in all situations so you should be wary.
When the client and the server need to synchronise with each other, they exchange information over the network.    Even when a single player game is running, the client and server are still completely separate and do not access each other's object instances.  If your code running on (say) the server side accesses object instances belonging to the client side, it will lead to random crashes and strange behaviour.  So don't do that!

I personally find it very helpful to split my mod into three top-level packages
  • client
  • common
  • server

This helps me clearly remember which classes are used on which side, and to make sure that I don't mix them up.

Further Links
~Client<-->Server communication
    Vanilla Client<-->Server Communication
    Client<-->Server communication using your own custom messages (SimpleNetworkWrapper)
    Thread safety with Network Messages