字节数组总是 return 十进制不是 c# 中的整数

Byte array always return decimal not integer in c#

我尝试使用 System.Net.Socket 在 c# 中使用客户端-服务器图创建一个简单的计算器。一切正常,但在服务器端,当我尝试转换从客户端接收的值时,它总是将值转换为十进制,而不是整数,但我尝试了很多次,仍然没有解决。

例如,当客户端输入 a=5 和 b=5 值时,在服务器端它变成 53 和 53。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace Server_Fix
{
    class Program
    {
        private static int SendVarData(Socket s, byte[] data)
        {
            int total = 0;
            int size = data.Length;
            int dataleft = size;
            int sent;

            byte[] datasize = new byte[4];
            datasize = BitConverter.GetBytes(size);
            sent = s.Send(datasize);

            while (total < size)
            {
                sent = s.Send(data, total, dataleft, SocketFlags.None);
                total += sent;
                dataleft -= sent;
            }
            return total;
        }

        private static byte[] ReceiveVarData(Socket s)
        {
            int total = 0;
            int recv;
            byte[] datasize = new byte[4];

            recv = s.Receive(datasize, 0, 4, 0);
            int size = BitConverter.ToInt32(datasize,0);
            int dataleft = size;
            byte[] data = new byte[size];


            while (total < size)
            {
                recv = s.Receive(data, total, dataleft, 0);
                if (recv == 0)
                {
                    data = Encoding.ASCII.GetBytes("exit ");
                    break;
                }
                total += recv;
                dataleft -= recv;
            }
            return data;
        }


        public static void Main()
        {
            byte[] data = new byte[1024];
            byte[] data1 = new byte[1024];
            byte[] data2 = new byte[1024];
            byte[] data3 = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);

            Socket newsock = new Socket(AddressFamily.InterNetwork,
                            SocketType.Stream, ProtocolType.Tcp);

            newsock.Bind(ipep);
            newsock.Listen(10);
            Console.WriteLine("Waiting for a client...");

            Socket client = newsock.Accept();
            IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine("Connected with {0} at port {1}",
                            newclient.Address, newclient.Port);

            string welcome = "CALCULATOR CLIENT-SERVER DIAGRAM!";
            data = Encoding.ASCII.GetBytes(welcome);
            int sent = SendVarData(client, data);

            string phepToan;
            int result=0;
            int a = 0, b = 0;
            while(true)
            {


                sent = SendVarData(client, Encoding.ASCII.GetBytes("Nhap vao so a: "));
                data1 = ReceiveVarData(client); 

                //Console.WriteLine("Client: " + Encoding.ASCII.GetString(data));
                sent = SendVarData(client, Encoding.ASCII.GetBytes("Nhap vao so b: "));
                data2 = ReceiveVarData(client); 
                //b = Convert.ToInt32(data2);
                sent = SendVarData(client, Encoding.ASCII.GetBytes("Cho biet phep tinh can dung la | + | - | * | / |: "));
                data3 = ReceiveVarData(client); 
                phepToan = Encoding.ASCII.GetString(data3);
                //a = Convert.ToString(Encoding.ASCII.GetString(data1));
                if (phepToan=="+")
                {
                    foreach (byte byteValue in data1)
                    {
                        a = Convert.ToChar(byteValue);  //It's always turn to Decimal values                                             
                    }
                    foreach (byte byteValue in data2)
                    {
                        b = Convert.ToChar(byteValue); //It's always turn to Decimal values
                    }
                    result = a + b; 

                    sent = SendVarData(client, Encoding.ASCII.GetBytes("Ket qua phep tinh: "+Convert.ToString(result)));
                }
                if (phepToan == "-")
                {

                }
                if (phepToan == "*")
                {

                }
                if (phepToan == "/")
                {

                }
            }
            Console.WriteLine("Disconnected from {0}", newclient.Address);
            client.Close();
            newsock.Close();
            Console.ReadLine();
        }
    }
}

============================================= =================== 客户端代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace Client_Fix
{
    class Program
    {
        private static int SendVarData(Socket s, byte[] data)
        {
            int total = 0;
            int size = data.Length;
            int dataleft = size;
            int sent;

            byte[] datasize = new byte[4];
            datasize = BitConverter.GetBytes(size);
            sent = s.Send(datasize);

            while (total < size)
            {
                sent = s.Send(data, total, dataleft, SocketFlags.None);
                total += sent;
                dataleft -= sent;
            }
            return total;
        }

        private static byte[] ReceiveVarData(Socket s)
        {
            int total = 0;
            int recv;
            byte[] datasize = new byte[4];

            recv = s.Receive(datasize, 0, 4, 0);
            int size = BitConverter.ToInt32(datasize,0);
            int dataleft = size;
            byte[] data = new byte[size];

            while (total < size)
            {
                recv = s.Receive(data, total, dataleft, 0);
                if (recv == 0)
                {
                    data = Encoding.ASCII.GetBytes("exit ");
                    break;
                }
                total += recv;
                dataleft -= recv;
            }
            return data;
        }

        public static void Main()
        {
            byte[] data = new byte[1024];
            int sent;
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);

            Socket server = new Socket(AddressFamily.InterNetwork,
                            SocketType.Stream, ProtocolType.Tcp);

            try
            {
                server.Connect(ipep);
            }
            catch (SocketException e)
            {
                Console.WriteLine("Unable to connect to server.");
                Console.WriteLine(e.ToString());
                return;
            }
            string input;
            data = ReceiveVarData(server);
            string stringData = Encoding.ASCII.GetString(data);
            Console.WriteLine(stringData);
            while (true)
            {

                data = ReceiveVarData(server);            
                Console.Write("Server: " + Encoding.ASCII.GetString(data));

                Console.WriteLine("You: " + input);
                sent = SendVarData(server, Encoding.ASCII.GetBytes(input));

                data = ReceiveVarData(server);
                Console.Write("Server: " + Encoding.ASCII.GetString(data));

                input = Console.ReadLine();
                //Console.SetCursorPosition(0, Console.CursorTop - 1);
                Console.WriteLine("You: " + input);
                sent = SendVarData(server, Encoding.ASCII.GetBytes(input));


                data = ReceiveVarData(server);
                Console.Write("Server: " + Encoding.ASCII.GetString(data));

                input = Console.ReadLine();
                //Console.SetCursorPosition(0, Console.CursorTop - 1);
                Console.WriteLine("You: " + input);
                sent = SendVarData(server, Encoding.ASCII.GetBytes(input));

                data = ReceiveVarData(server);
                Console.WriteLine("Server: " + Encoding.ASCII.GetString(data));
            }

            Console.WriteLine("Disconnecting from server...");
            server.Shutdown(SocketShutdown.Both);
            server.Close();
            Console.ReadLine();
        }
    }
}

假设 byteValue 是 53,即字符“5”的代码点。

然后

Convert.ToChar(byteValue)

会给出 53。没关系,C# 中的字符有一个数值,这是它们在字符 table.

中的序数

解决您的问题的一种方法是:

var a = int.Parse(ASCIIEncoding.ASCII.GetString(new byte[] { bytevalue }));

或者,再次进行一些推测,更有可能:

var a = int.Parse(ASCIIEncoding.ASCII.GetString(data1));

此处,字符数字“5”通过线路传输时的数字表示(如 53)将在 ASCII table 中查找,给出“5”,然后解析为所需的整数。

但它并没有解决整个代码的根本问题,这需要更全面地规划如何以可靠的方式编码、传输和随后解码信息位。