Alright. Since we've already done a single-threaded networked application, what is there to do next? Why a multithreaded one of course! But let's go the extra mile and use some
async code too. This one turned out to be more complex than I envisioned, but bear with me because it can do more. Hold tight, it will be fun.
Please note that this section does not have any
Socket programming. That's something completely different and it will be covered in a later section.
I always find video games as a great way of teaching programming concepts, languages, and libraries. But since I want to keep this tutorial series as "GUI-less," as possible we're going to do some text (console) based gaming. Get ready to party like its 1989 because George H. W. Bush has been elected, Tim Burton is directing a Batman film, Milli Vanilli is topping the charts, and Game Boys are all the rage; We're making a BBS game!! (sort-of)
Just as a side note, if you want to make a real video game, it would be much, MUCH better to use UDP instead of TCP for most cases. TCP here is optimal since we're doing text based gaming only and any of the games that we have on the server should be turn-based. UDP is a much better choice if your networked game runs in real time.
If you haven't read the previous section, TCP Chat, go do so so you can familiarise yourself with
TcpListener. Part of the design of the server side is so that we can switch out different games. Because of time constraints, I've only implemented one game called "Guess My Number," which is single player. I also wanted to do Tic-Tac-Toe as well (multi-player), but I'll leave that an exercise for you. It shouldn't be too difficult.
We only should have two separate projects in our solution for this section. One being the
TcpGamesServer and the other the
TcpGamesClient. Our namespace for both will be
We also will be using the same
_isDisconnected() method to check for ungraceful disconnects. Note that it's name is slightly different in the server code. Here it is again: