Search code examples
c#tcptcpclienttcplistener

TCP message does not equal to what is sent in C#. How do I make it so it is?


When I send the message to the client and I try to check it with an if statement it doesn't equal to what I sent from the server.

What I want to do is: I want to send the keyword (here it's poop) and check it with an if statement on the client part. If it finds that keyword with the if statement I want to execute some code.

For example:

Client code:

try {
            TcpClient tcpclnt = new TcpClient();
            Console.WriteLine("Connecting.....");
            
            tcpclnt.Connect("127.0.0.1",8001);
            
            Console.WriteLine("Connected");
            
            Stream stm = tcpclnt.GetStream();
                        
            ASCIIEncoding asen= new ASCIIEncoding();
            
            
            while(true)
            {
                byte[] bb=new byte[100];
                int k=stm.Read(bb,0,100);
                for (int i=0;i<k;i++)
                {
                    var msg = Convert.ToChar(bb[i]).ToString();
                    if(msg == "poop")
                    {
                        Console.WriteLine("Poop executed.");
                    }
                }
            }
            
            
            
            
            
            
        }
        
        catch (Exception e) {
            Console.WriteLine("Error..... " + e.StackTrace);
        }

Server code (when the console reads my input I type "poop"):

try {
        IPAddress ipAd = IPAddress.Parse("127.0.0.1");
         

        TcpListener myList=new TcpListener(ipAd,8001);

        myList.Start();
        
        Console.WriteLine("The server is running at port 8001...");    
        Console.WriteLine("The local End point is  :" + 
                          myList.LocalEndpoint );
        Console.WriteLine("Waiting for a connection.....");
        
        Socket s=myList.AcceptSocket();
        Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
        
        
        
        

        ASCIIEncoding asen=new ASCIIEncoding();
        while(true)
        {
            
            Console.Write("Msg to send: ");
            var f = Console.ReadLine();
            s.Send(asen.GetBytes(f));
        }
        s.Close();
        myList.Stop();
            
    }
    catch (Exception e) {
        Console.WriteLine("Error..... " + e.StackTrace);
    } 

Solution

  • The problem with your code is that you iterate over the byte array in which you wrote the received data. Therefore the message variable does always contain only one letter of your received message and is therefore never "poop" but "p", "o", "o", "p". To solve this issue you can use System.Text.Encoding to convert your byte array to a string:

    byte[] bb = new byte[100];
    int k = stm.Read(bb, 0, 100);
    var msg = System.Text.Encoding.UTF8.GetString(bb, 0, k);
    
    if(msg == "poop")
    {
       // Do something
    }
    

    An even better solution would be to write back your received data into a temporary array until a defined end of string signal is received and only convert the temporary array if you are sure that everything is received.