将十六进制字符串发送到TCP套接字

时间:2016-10-13 11:30:01

标签: c# sockets tcp

我使用TCP / IP将VideoJet Printer连接到我的PC,创建C#windows dekstop应用程序来读写TCP Socket。当我使用hercules软件在Hex字符串下面进行选择时[当HEX Checkbox勾选时]它正在响应但是当我从我的C#代码发送相同的十六进制字符串时它没有响应 请在我的代码中建议我在哪里做错了

Hercules Reponse

try
        {
            client = new TcpClient("192.168.2.1", Convert.ToInt32("3001"));

            // Translate the passed message into ASCII and store it as a Byte array.
            Byte[] data = HexString2Bytes(richTextBox3.Text);
            stream = client.GetStream();

            // Send the message to the connected TcpServer. 
            stream.Write(data, 0, data.Length);
            Console.WriteLine("Sent: {0}",richTextBox3.Text);

            // Receive the TcpServer.response.
            data = new Byte[65000];
            var readStream = new MemoryStream();
            int readBytes = stream.Read(data, 0, data.Length);
            while (readBytes > 0)
            {
                readStream.Write(data, 0, readBytes);
                readBytes = stream.Read(data, 0, data.Length);
            }
            var responseData = Encoding.ASCII.GetString(readStream.ToArray());
        }
        catch (Exception ex)
        {
            string errormsg = ex.ToString();
        }


private byte[] HexString2Bytes(string hexString)
    {
        //check for null
        if (hexString == null) return null;
        //get length
        int len = hexString.Length;
        if (len % 2 == 1) return null;
        int len_half = len / 2;
        //create a byte array
        byte[] bs = new byte[len_half];
        try
        {
            //convert the hexstring to bytes
            for (int i = 0; i != len_half; i++)
            {
                bs[i] = (byte)Int32.Parse(hexString.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Exception : " + ex.Message);
        }
        //return the byte array
        return bs;
    }

命令十六进制字符串 A503CA002C000000E4411251C0000000B60000003C0050006100720061006D0073003E00200020003C0043006F006C002000690064003D00220044006500760069006300650073002F0050004800640073002F0031002F005000720069006E00740049006E0066006F0072006D006100740069006F006E002200200067006500740046006C006100670073003D002200320022002000670065007400440065007000740068003D0022002D003100220020002F003E003C002F0050006100720061006D0073003E000000

1 个答案:

答案 0 :(得分:0)

我其实不知道,为什么你必须做一个While循环。当您从服务器 readBytes 收到字节数时,您可以使用这样的编码完成代码:

string responseData = Encoding.ASCII.GetString(data,0,readbytes);

要获取更多信息,您可以在此链接中找到 https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient?view=net-5.0