private void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            //NetworkStream clientStream = tcpClient.GetStream();
            var rw = new SocketReaderWriter(tcpClient);
            if (OnClientConnect != null)
                OnClientConnect(rw);

            byte[] message = new byte[4096];
            //int bytesRead;
            //char nullChar = new char();
            StringBuilder sb = new StringBuilder();
            ASCIIEncoding encoder = new ASCIIEncoding();
            while (tcpClient.Connected)
            {
                //bytesRead = 0;

                try
                {
                    //blocks until a client sends a message
                    string msg = rw.ReadSocketMessage();
                    try
                    {

                        if (!string.IsNullOrEmpty(msg) && OnClientMessage != null)
                            OnClientMessage(rw, msg);
                        else if (!tcpClient.Connected)
                        {
                            //the client has disconnected from the server
                            break;
                        }

                    }
                    finally
                    {
                        // decrements the channel counter without sending a message
                        rw.EndChannel();
                        if (tcpClient.Connected)
                            rw.EndChannelMessage();
                    }

                }
                catch
                {
                    //a socket error has occured
                    break;
                }

                //message has successfully been received

                //  System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
            }
            tcpClient.Close();
            if (OnClientDisconnect != null)
                OnClientDisconnect(rw);
        }
 private void SetConnected(bool AConnected)
 {
     if (AConnected)
     {
         if (_client == null || !_client.Connected)
         {
             _client = new TcpClient();
             IPEndPoint serverEndPoint = new IPEndPoint(_ip, _port);
             _client.Connect(serverEndPoint);
             _io = new SocketReaderWriter(_client);
         }
     }
     else
     {
         if (_client != null)
         {
             if (_client.Connected)
                 _client.Close();
             _client = null;
             _io = null;
         }
     }
 }