【问题标题】:How to open a Telnet session in C# program and send commands and receive responses programmatically?如何在 C# 程序中打开 Telnet 会话并以编程方式发送命令和接收响应?
【发布时间】:2021-10-18 21:34:03
【问题描述】:

我有一台 optoma 投影仪,我想从 C# 程序内部使用 Telnet 会话与其通信。使用各种包装器和 Nuget 包,我能够启动 telnet 会话,但我无法在我的 C# 程序中传达命令或接收响应。

在普通的 windows cmd 中,如果我写 Telnet 192.168.222.127,telnet 会话就会开始。投影机以 ASCII 格式 (https://www.optoma.de/uploads/RS232/DS309-RS232-en.pdf) 响应命令,并根据命令失败或通过返回“F”或“P”。要将亮度更改为 10,我会这样做:

  1. 打开 Telnet 连接:telnet 192.168.222.127
  2. 发送命令将亮度更改为 10 : ~0021 10
  3. 在更改亮度的命令中,会话将以“P”响应。 Telnet Terminal Commands

我想对 C# 程序做同样的事情,但我被卡住了。大多数答案都指向过时的包和链接。我是 Telnet 和通信协议的新手,需要这方面的帮助。谢谢。

【问题讨论】:

  • 只需使用Telnet library
  • 或者,如果您喜欢冒险,就每天使用香草Tim Shaw Demtel 插座
  • stackoverflow.com/questions/390188/c-sharp-telnet-library - 有一些 lib 建议(SO 的主题外)和至少一个答案,其中包含一些用于戳 telnet 服务器的粗略代码
  • 我尝试了不同的 telnet 库,通过所有这些库,我都能够连接到投影仪。问题是我将 ascii 命令作为“~0000 1\n”发送。一旦我将其更改为“~0000 1\r\n”,投影仪就可以理解命令。这可能是一件显而易见的事情,但直到我尝试过才知道。

标签: c# telnet projector


【解决方案1】:

如果你只是想连接设备,发送命令并读取响应,简单的 C# TcpClient 就足够了。它为 TCP 网络服务提供客户端连接,这正好适合我的情况。

用于建立连接:

using system.net.sockets;

    public void EstablishConnection(string ip_address, int port_number=23){
        try
        {
            client = new TcpClient(ip_address, port_number);
            if (DEBUG) Console.WriteLine("[Communication] : [EstablishConnection] : Success connecting to : {0}, port: {1}", ip_address, port_number);
            stream = client.GetStream();
        }
        catch
        {
            Console.WriteLine("[Communication] : [EstablishConnection] : Failed while connecting to : {0}, port: {1}", ip_address, port_number);
            System.Environment.Exit(1);
        }
    }

用于发送和接收响应:

    public string SendMessage(string command)
    {
        // Send command
        Byte[] data = System.Text.Encoding.ASCII.GetBytes(command);
        stream.Write(data, 0, data.Length);
        if (DEBUG) Console.Write("Sent : {0}", command);

        WaitShort();

        // Receive response
        string response = ReadMessage();
        if (DEBUG) Console.WriteLine("Received : {0}", response);

        return response;
    }

    public string ReadMessage()
    {
        // Receive response
        Byte[] responseData = new byte[256];
        Int32 numberOfBytesRead = stream.Read(responseData, 0, responseData.Length);
        string response = System.Text.Encoding.ASCII.GetString(responseData, 0, numberOfBytesRead);
        response = ParseData(response);
        if (response == "SEND_COMMAND_AGAIN")
        {
            if (DEBUG) Console.WriteLine("[ReadMessage] : Error Retreiving data. Send command again.");
        }
        return response;
    }

您可以根据自己的要求解析来自服务器的响应。

【讨论】:

    猜你喜欢
    • 2011-04-19
    • 2014-09-26
    • 2020-12-23
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多