使用 CR 向 C# 中的 TCP 服务器发送命令


public void ClientSend(string msg)
{
    stream = client.GetStream(); //Gets The Stream of The Connection
    byte[] data; // creates a new byte without mentioning the size of it cuz its a byte used for sending
    data = Encoding.Default.GetBytes(msg); // put the msg in the byte ( it automaticly uses the size of the msg )
    int length = data.Length; // Gets the length of the byte data
    byte[] datalength = new byte[4]; // Creates a new byte with length of 4
    datalength = BitConverter.GetBytes(length); //put the length in a byte to send it
    stream.Write(datalength, 0, 4); // sends the data's length
    stream.Write(data, 0, data.Length); //Sends the real data
}

我正在尝试将命令发送到伟迪捷打印机 TTO,这是我的 TCP 服务器,当我通过大力神(TCP 客户端(发送GST<cr>时,它会将命令作为 GST 正确发送到打印机,而当我从我的 C# TCP 客户端实用程序发送textbox.text = "GST" + "r"打印机时没有响应。在Hercules中观察到,当我在Hercules TCP服务器中发送textbox.text = "GST" + "r"时,它接收GSTr而不是GST,这意味着CR正在与字符串一起传递,它将作为字符串传递。

richtextbox.AppendText("rn" + now.ToString() + " Sent : rn" + textbox.Text + "r");
基本上听起来您需要

更改处理RichTextBox文本的方式。如果要将r用作换行符,请使用:

string text = string.Join("r", richtextbox.Lines);
ClientSend(text);

正如评论中提到的,您几乎肯定不想使用Encoding.Default......您应该找出服务器期望的编码,并使用它。如果您可以自己指定,我会使用 UTF-8:

// Note: there's no benefit in declaring the variable in one statement
// and then initializing it in the next.
byte[] data = Encoding.UTF8.GetBytes(message);

而不是发送"GST"+"\r",尝试发送"GST"+(char(13;。

最新更新