Search code examples
c#tcpclienttcp

switch string statement not working?


$I already convert the data i receive. but when i try to put it in a switch statment, it dosent do anything. as you can see there is a MessageBox.Show(rData) which shows the data i receive and its good. only on the switch. any suggestion?

    string readData = null;

    public void getMessage()
    {
        while (true)
        {
            serverStream = clientSocket.GetStream();
            int buffsize = 0;
            byte[] inStream = new byte[10025];
            buffsize = clientSocket.ReceiveBufferSize;
            serverStream.Read(inStream, 0, buffsize);
            string rData = Encoding.ASCII.GetString(inStream);
            readData = "" + rData;
            //MessageBox.Show(rData);

            switch (readData)
            {
                case ("Overview"):
                    MessageBox.Show("Start");
                    break;
                default:
                    break;
            }
        }
    }

Solution

  • byte[] inStream = new byte[10025];
    

    you have initialized a byte array of with length 10025. If your incoming data is not that long you will get bunch \0 characters (string terminator) at the end when you convert it into string.

    Those characters will not show up when you called MessageBox.Show since they are invisible characters.

    so the solution is to initialize the array to the size of the actual data

    OR call .Replace("\0", ""); on the string before you feed it into the switch statement