我是Telnet的新手,我需要在WPF(C#)中编写一个小程序,通过telnet向设备发送和接收命令。
它的开头是:
- 发送命令“telnet 192.168.0.50”(为了连接到设备)
- 然后发送“用户”和“密码”
- 然后开始向设备发送和接收数据,并且所有通信都需要出现在WPF日志屏幕上。
醇>
我在Google上搜索了有关如何操作的信息,但我找不到对我有帮助的内容。
我在这里问,因为我很无助,我需要一些指示才能从某个地方开始......我真的很感谢你的帮助。
谢谢。
答案 0 :(得分:0)
粗略地(在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
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
答案 1 :(得分:0)
我有一个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。