Вопрос

I am trying to have a client send a command to my service, that command being "R". But when I try to make an IF statement it will not register the "R" that came in via TCP as being equal to a string R that I have made in my program. Here is some of my code.

    byte[] message = new byte[1024];
        byte[] command = Encoding.ASCII.GetBytes("R");
        stream.Read(message, 0, message.Length);
        string messageIn = Encoding.ASCII.GetString(message);
        //updateUI("New Message =  " + messageIn);
        string commandString = Encoding.ASCII.GetString(command);

         if (Encoding.ASCII.GetString(message) == Encoding.ASCII.GetString(command))

As you can see, I was of the impression that taking "R" into bytes and then out of bytes would have caused this problem hence the giant if statement. However not a single one of these conditions returns true as my if block never runs.

I know that it is returning "R" because when I output it to a textbox, that is what gets printed. Is the very act of transfering it VIA tcp changing the string somehow?

Это было полезно?

Решение

Aside from the vast number of pointless comparisons you're making, the first problem is that you're ignoring the result of Stream.Read... and instead creating a string out of the whole 1024 bytes within message. If you change it to:

int bytesRead = stream.Read(message, 0, message.Length);
string messageIn = Encoding.ASCII.GetString(message, 0, bytesRead);

... then you'd be in a much better position. However, that's probably still not good enough, unless that's all that's going to be sent. You're dealing with a stream, but I suspect you're thinking about it as if it's message-oriented - as if a single Write on one end of the connection will map to a single Read on the other end. That's not how stream-oriented protocols work. If you have a logical "message" then when reading from the stream you might end up with part of a message, multiple messages, anything. Common ways of fixing this are:

  • Include a length prefix before each message
  • Use a separator (e.g. a line break for text-based protocols)

See Marc Gravell's blog post on this for more details.

Additionally, if your protocol is text-based, it would be a good idea to create a StreamReader around the stream so that you can just read text (e.g. a line at a time) instead of converting all over the place.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top