First, it waits for data to come in on the network stream. Everything I send over a stream socket is preceded by exactly 4 bytes, which is a UInt32 that lets the receiving data reader know how much data to read. There are other ways to handle the reading data from network streams, but this is the way I chose.
Everything that’s sent from server to client and back is serialized into XML, so it’s expecting the incoming data to be a string. It sends that string to the Utilities.Deserialize method, which will convert the string into an object. I’ll go over how the serialization works in my next post.
Next, we send that object to ReceiveDataFromClient for processing. Every object that’s sent over the network stream has a common interface. By checking the type of class being received, the receiver knows which method to call that will execute the logic necessary to process it. For example, if the data coming in is of type Message, there could be a ShowMessage method on it that will display the message according to its properties.
This loop repeats indefinitely until an error is encountered. The example above merely logs the player out, but you could also include advanced error handling depending on the situation, such as reconnection attempts, etc.
Well, that’s all for the socket server, I think! In later posts, I’ll talk about how the serialization works and how to construct your classes that will be used to send data over the network (also called Data Transfer Objects or DTOs).
Take care!
– Jared