【问题标题】:Send and Receive commands via Telnet in C#在 C# 中通过 Telnet 发送和接收命令
【发布时间】:2014-09-26 18:33:21
【问题描述】:

我是 Telnet 新手,我需要用 WPF (C#) 编写一个小程序,通过 telnet 向设备发送和接收命令。

开头是:

  1. 发送命令“telnet 192.168.0.50”(为了连接到设备)
  2. 然后发送“用户”和“密码”
  3. 然后开始向设备发送和接收数据,所有通信需要显示在 WPF 日志屏幕上。

我在 Google 上搜索了有关如何操作的信息,但没有找到对我有帮助的信息。

我在这里问是因为我很无助,我需要一些方向才能从某个地方开始......我非常感谢你的帮助。

谢谢。

【问题讨论】:

标签: c# wpf ip-address communication telnet


【解决方案1】:

我有一个 GitHub 项目 https://github.com/9swampy/Telnet/,也作为 NuGet dll https://www.nuget.org/packages/Telnet 发布,这将允许您:

using (Client client = new Client(server.IPAddress.ToString(), server.Port, new System.Threading.CancellationToken()))
{
  await client.TryLoginAsync("username", "password", TimeoutMs);
  client.WriteLine("whatever command you want to send");
  string response = await client.TerminatedReadAsync(">", TimeSpan.FromMilliseconds(TimeoutMs));
}

这应该可以让您在应用程序中实现您想要的,如果您想查看使这一切正常运行的代码,您可以查看 GitHub。

【讨论】:

    【解决方案2】:

    大致(在 VB 中,但应该很容易转换为 c#)。您只需添加位即可将用户名和密码写入流

    Dim Data As String
    Dim reader As StreamReader = Nothing
    Dim NsStream As NetworkStream = Nothing
    dim address as IPAddress = IPAddress.Parse("192.168.0.50")
    Dim ipe As New IPEndPoint(address, port)
    Dim telnetSocket As New Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
    
    telnetSocket.Connect(ipe)
    
     If (telnetSocket.Connected) Then
         Try
        
             'if is necessary to send a command
             'telnetSocket.Send(Encoding.ASCII.GetBytes("Command to execute"))
    
             NsStream = New NetworkStream(telnetSocket, True)
             reader = New StreamReader(NsStream)
    
             Do While (Not reader.EndOfStream)
    
                 ' Read the line of data
                  Data = reader.ReadLine()
                 'Do whatever with data
             Loop
        
        Catch ex As Exception
               Msgbox(ex.message)
        Finally
                Try
                    If reader IsNot Nothing Then
                        reader.Close()
                    End If
                Catch ex As Exception
                End Try
                Try
                    If NsStream IsNot Nothing Then
                        NsStream.Close()
                    End If
                Catch ex As Exception
                End Try
            End Try
    
    end if
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-02
      • 2020-09-01
      • 2015-02-19
      • 2015-11-12
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 2011-01-28
      相关资源
      最近更新 更多