如何在c#程序中打开Telnet会话并以编程方式发送命令和接收响应?



我有一个光学投影仪,我想从c#程序内部使用Telnet会话与它通信。使用各种包装器和Nuget包,我能够启动telnet会话,但我不能在我的c#程序中通信命令或接收响应。

在正常的windows命令行中,如果我写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终端命令

我想用c#程序做同样的事情,但我被卡住了。大多数答案都指向过时的软件包和链接。我是新的Telnet和通信协议,需要帮助关于这一点。谢谢你。

如果您只是想连接到设备,发送命令并读取响应,简单的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;
}

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

最新更新