Consumer Client

This class contains the Consumer that pairs up with the Producer in the server class. This class is also responsible for instantiating the Listener class with the start() function.

Note that the consumer is doing the ASCII encoding of the bytes.


using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Server
{
    class Client
    {
        private bool running;
        private Listener listener;
        private Task threadRec;

        public void start(string address, int port) // server
        {
            listener = new Listener(address, port);
            listener.start();

            threadRec = Task.Factory.StartNew(new Action(processMsgs), TaskCreationOptions.LongRunning);
            running = true;
        }

        private void processMsg(string msg)
        {
            // do something with the message that the server sent us.
            // maybe populate a ListView with the messages
        }

        private void processMsgs()
        {
            string message = "";
            byte[] buffer;

            while (running)
            {
                buffer = null;

                while (listener.receivedBytes.Count == 0) { Thread.Sleep(50); } // stay here

                while (listener.receivedBytes.TryDequeue(out buffer)) // consumer
                {
                    if (buffer != null)
                    {
                        try
                        {
                            message = Encoding.ASCII.GetString(buffer, 0, buffer.Length).TrimEnd(' ', '\0');
                        }
                        catch (Exception e)
                        {
                            listener.logger.log("EXCEPTION 1 ExternalCommandListener: " + e.Message);
                        }

                        processMsg(message);
                    }

                    Thread.Sleep(25);

                }
            }
        }
    }
}