我正在编写一些软件来与通过TCP / IP连接的激光标记进行通信。我正在使用套接字测试来模拟这台机器。
我希望能从机器中收到一组特定的回复:
return read_csv(newdataset)
行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;
}
}
有效,但它返回'“VS 1 \ r \ n”',导致'if'语句评估为false。
有没有办法只返回流中输入的信息?
答案 0 :(得分:1)
你可以修剪它:
string response = System.Text.Encoding.ASCII.GetString(Data, 0, bytes).Trim();