簡體   English   中英

C#TCP / IP服務器響應文本

[英]C# TCP/IP Server Response Text

我正在編寫一些軟件來與通過TCP / IP連接的激光刻印機進行通信。 我正在使用套接字測試來模擬這台機器。

我期望從機器中收到一組特定的響應,並將它們放入代碼中:

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); 可以,但是返回“ VS 1 \\ r \\ n”,導致if語句的計算結果為false。

有沒有一種方法可以僅從流中返回鍵入的信息?

您可以修剪一下:

string response = System.Text.Encoding.ASCII.GetString(Data, 0, bytes).Trim();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM