TCP Chat - Viewer

This is also a much tinier one like the Messenger, in fact, most of the code is pretty similar.  Once it has connected to the server, it will get a "hello," message, and then keep printing out messages until the user presses Ctrl-C.



Similar to the Messenger, we're using the constructor of TcpClient that doesn't start a connection.  We do that in our Connect() method.  If we're connected, we immediately send over the text viewerto tell it that we are, well, a Viewer client.  If we are still connected, then we're safe to assume that the server recognises us as a viewer and will send us messages.  As this point, the server has already sent us a message with "Welcome to the 'SERVER_NAME' Chat Server".  Though, we don't find out about it until we enter ListenForMessages().

In that function, if we are connected, we test to see if there is a new message or not.  If there is, TcpClient.Available will report how many bytes are incoming.  If so, we then try to read that many bytes from the NetworkStream.   The call to Read() will block until that many bytes have been read in.  Once the message is received, it will print it out to the user.  Like the other programs, we also sleep for 10 milliseconds to conserve CPU resources.  Then we do a check for that FIN/ACK packet and a check to see if the user pressed Ctrl-C.

Once we've exited the while(Running) loop, we clean up any network resources that we have left over.

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