[英]C# TCP/IP Server Response Text
I'm writing a bit of software to communicate to a laser marker which connects over TCP/IP. 我正在编写一些软件来与通过TCP / IP连接的激光刻印机进行通信。 I am using socket test to simulate this machine.
我正在使用套接字测试来模拟这台机器。
I am expecting to receive a particular set of responses from the machine which I have put into my code: 我期望从机器中收到一组特定的响应,并将它们放入代码中:
public static bool CheckConnection(string com, string server, int port)
{
try
{
Console.WriteLine("Setting up TCP/IP");
TcpClient client = new TcpClient(server, port);
NetworkStream stream = client.GetStream();
Byte[] Data = System.Text.Encoding.ASCII.GetBytes(com);
stream.Write(Data, 0, Data.Length);
Console.WriteLine("Sent: {0}", com);
Data = new Byte[256];
Int32 bytes = stream.Read(Data, 0, Data.Length);
string response = System.Text.Encoding.ASCII.GetString(Data, 0, bytes);
Console.WriteLine("Response: {0}", response);
if (response != "VS 1")
{
Console.WriteLine("Connection Test failed! Invalid response.");
stream.Close();
client.Close();
return false;
}
else
{
Console.WriteLine("Connection Test Successful!");
stream.Close();
client.Close();
return true;
}
}
catch (SocketException e)
{
Console.WriteLine("Socket Exception: {0}", e);
return false;
}
}
the line string response = System.Text.Encoding.ASCII.GetString(Data, 0, bytes);
行
string response = System.Text.Encoding.ASCII.GetString(Data, 0, bytes);
works but it returns '"VS 1\\r\\n"' causing the 'if' statement to evaluate to false. 可以,但是返回“ VS 1 \\ r \\ n”,导致if语句的计算结果为false。
Is there a way to return just the typed information from the stream? 有没有一种方法可以仅从流中返回键入的信息?
您可以修剪一下:
string response = System.Text.Encoding.ASCII.GetString(Data, 0, bytes).Trim();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.