C# TCP/IP 服务器响应文本
C# TCP/IP Server Response Text
我正在编写一些软件来与通过 TCP/IP 连接的激光打标机进行通信。我正在使用socket测试来模拟这台机器。
我希望收到我已放入代码中的机器的一组特定响应:
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;
}
}
行 string response = System.Text.Encoding.ASCII.GetString(Data, 0, bytes);
有效,但它 returns '"VS 1\r\n"' 导致 'if' 语句评估为 false。
有没有办法 return 只从流中输入信息?
您可以trim:
string response = System.Text.Encoding.ASCII.GetString(Data, 0, bytes).Trim();
我正在编写一些软件来与通过 TCP/IP 连接的激光打标机进行通信。我正在使用socket测试来模拟这台机器。
我希望收到我已放入代码中的机器的一组特定响应:
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;
}
}
行 string response = System.Text.Encoding.ASCII.GetString(Data, 0, bytes);
有效,但它 returns '"VS 1\r\n"' 导致 'if' 语句评估为 false。
有没有办法 return 只从流中输入信息?
您可以trim:
string response = System.Text.Encoding.ASCII.GetString(Data, 0, bytes).Trim();