Question

My server is sending the following data:

{
  "command": 23
}

My client is receiving the following data:

"{\0\r\0\n\0 \0 \0\"\0c\0o\0m\0m\0a\0n\0d\0\"\0:\0 \02\03\0\r\0\n\0}\0"

As you can see I'm receving the data sent, but with those \0 mixed with it. What is causing this? Maybe something with the encoding?

Method from server which sends the data:

public void GetBasicInfo()
        {
            JObject o = new JObject();

            o.Add(COMMAND, (int)Command.GetBasicInfo);

            byte[] package = GetBytes(o.ToString());
            System.Diagnostics.Debug.WriteLine(o.ToString());
            networkStream.Write(package, 0, package.Length);
            networkStream.Flush();
        }

private static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }

Method from client which reads the data:

private void CommsHandler(TcpClient tcpClient)
        {
            NetworkStream networkStream = tcpClient.GetStream();

            while (true)
            {
                try
                {
                    string message = ReadResponse(networkStream);
                    System.Diagnostics.Debug.WriteLine(message);
                    ParseMessage(message);
                }
                catch (Exception)
                {
                    break;
                }

            }

            Logger.Log(LogType.Warning, "Communication with server closed");

            tcpClient.Close();
            SearchForServer();
        }

private static string ReadResponse(NetworkStream networkStream)
        {
            // Check to see if this NetworkStream is readable.
            if (networkStream.CanRead)
            {
                var myReadBuffer = new byte[256]; // Buffer to store the response bytes.
                var completeMessage = new StringBuilder();

                // Incoming message may be larger than the buffer size.
                do
                {
                    var numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length);
                    completeMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
                } while (networkStream.DataAvailable);

                return completeMessage.ToString();
            }
            return null;
        }
Était-ce utile?

La solution

As you can see I'm receving the data sent, but with those \0 mixed with it. What is causing this? Maybe something with the encoding?

Yes. It's this method:

private static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

It's copying the char data in binary form - two bytes per character. Don't use this at all - just use Encoding.GetBytes, having chosen a suitable encoding... I'd suggest Encoding.UTF8. Use the same encoding on the receiving side. Note that you can't just use Encoding.GetString as you may receive data which ends half way through a character (if you have any non-ASCII data).

I'd also recommend against using DataAvailable as an indication of whether a message has finished or not. If you're sending multiple messages on the same stream, you should either length-prefix each message (probably the simplest approach) or use some specific data to indicate the end of the stream.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top