Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

c# - Send a value by socket and read the value by reader.ReadInt32() changes value

I am trying to send a value by socket .So i have two parts in my project Client and server .

The client sends a value to server using this code :

           System.IO.BinaryWriter binaryWriter =
           new System.IO.BinaryWriter(networkStream);
           binaryWriter.Write(1);
           binaryWriter.Write(2);
           binaryWriter.Flush();

So in other part i need to read the two values i mean 1 and 2;

So in server part i have this code :

  static void Listeners()
        {

        Socket socketForClient = tcpListener.AcceptSocket();
        if (socketForClient.Connected)
        {
            NetworkStream networkStream = new NetworkStream(socketForClient);


            while (true)
            {
                  List<int> variables = new List<int>();
                using (var reader = new BinaryReader(networkStream))
                {
                    for (int i = 0; i < 2; i++)
                    {
                        int t = reader.ReadInt32();
                        variables.Add(t);
                    }
                }

      }
   }
}

As you can see i hold the values in variables list .but it doesn't work .i mean in server part i can't get the values 1 and 2 and my values is like this :841757955

best regards.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

and my values is like this :841757955

Always worth sticking that number in the Windows calculator and convert that to hex. You get 0x322C3503.

Which looks a lot like ASCII, a string with 3 characters that encodes "5,2". In other words, your real code doesn't resemble your snippet at all, you don't actually use the BinaryWriter.Write(Int32) overload, you used BinaryWriter.Write(String).

Sure, that can't work, you can't write a string and expect it to be readable as raw integers. Fix your code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...