TCP Games - Client

Now the last thing that we have to do is write the client code.  Remember to add the Packet to the client project.


Don't forget to include the Newtonsoft.Json package in this project too.



This code is somewhat similar to the clients that we wrote for the TCP Chat application.  Because of the packets, we have added a Dictionary at the top the store functions and to dispatch messages that we've received.  In the constructor we setup the TcpClient (but don't connect it) and init some other resources.  _cleanupNetworkResources() will close the TcpClient for us and it's NetworkStream.

The Connect() method is a bit more robust than last time.  First it will try to create the connection in a try-catch block.  If it wasn't successful, then nothing else will work.  If successful, we yank out the underlying NetworkStream and hook up our Packet dispatchers.  Disconnect() will attempt a graceful disconnect with the server by sending a bye Packet.

The Run() method of this class is also the most important part.  If we're connected, _handleIncomingPackets() will do what the name says.  Then after that there is a short nap to save on CPU usage and a check for any type of disconnect.  After the main loop, we give it one second for any other incoming packets to be handled.  Lastly, we clean up the network resources.

_sendPacket() will asynchronously send a Packet over to the server.  Likewise _handleIncomingPackets() will check for available messages and then dispatch them to their correct handlers.

Since we have three different types of commands that can be sent in a Packet, we've got three handlers:

  • _handlebye() will shutdown the client
  • _handleMessage() will print out the contents of the message field to the console
  • _handleInput() will request the user for some input from the command line and then send a response to the server


_isDisconnected() is used to check for ungraceful disconnects from the server (like always).  And the last bits of the file are for program execution.

© – Made using & love.
Back to Top of Page
This site uses cookies.