簡體   English   中英

字節數組在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#中的char具有一個數字值,這是它們在字符表中的序數。

解決您的問題的一種方法是:

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

或者,再次有一些猜測,更有可能:

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

在這里,字符數字“ 5”的數字表示通過電線(如53)時,將在ASCII表中查找,給出“ 5”,然后解析為所需的整數。

但是,它不能解決整個代碼的根本問題,而這將需要對信息位如何以可靠的方式進行編碼,傳輸和隨后解碼的更徹底的計划。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM