【发布时间】:2018-07-10 14:36:27
【问题描述】:
我有以下代码成功地允许我打开一个到 telnet 服务器的套接字并协商适当的握手,如下所示。
Established Connection to 192.168.10.33
FF FD 18 FF FD 20 FF FD 23 FF FD 27 FF FD 24 ÿy.ÿy.ÿy#ÿy'ÿy$
FF FB 03 FF FD 01 FF FD 22 FF FD 1F FF FB 05 FF ÿû.ÿy.ÿy"ÿy.ÿû.ÿ
FD 21 y!
FF FB 01 FF FD 06 FF FD 00 ÿû.ÿy.ÿy.
FF FB 03 FF FB 01 ÿû.ÿû.
我被卡住并且似乎缺少一些基本的东西是如何在上述握手完成后从 telnet 读回连续的数据流。
这是概念。我发送一个存储在 xml 文件中的 telnet 命令,并希望能够将来自 telnet 服务器的响应作为变量读回,我可以使用该变量将其显示回控制台并发送到应用程序中的其他方法。 请参阅下图以了解使用腻子作为客户端的说明:
我也无法收到 0x0D 0x0A Welcome to the Tesira Text Protocol Server 0x0D 0x0A 欢迎消息,但我认为这只是更广泛问题的症状。
我可以发送命令:
Console.WriteLine("Item: "+item.Attributes["commandText"].Value);
byte[] commandBytes = Encoding.ASCII.GetBytes(item.Attributes["commandText"].Value + " \r\n");
s.Send(commandBytes);
但是我对如何读回数据有点迷茫。 下面的代码是我编写的用于处理套接字连接和握手方面的类。
我真的不知道下一步该去哪里,找了几个小时寻找一个我能理解的好教程,但没有找到任何真正帮助我的东西。
class telnetHandshake
{
private static byte[] writeBuffer;
private static byte[] readBuffer;
private static int bc;
public void telnetInit()
{
IPAddress address = IPAddress.Parse("192.168.10.33");
int port = 23;
IPEndPoint endpoint = new IPEndPoint(address, port);
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
s.Connect(endpoint);
Console.WriteLine("Established Connection to {0}", address);
byte[] readBuffer = new byte[1024];
bc = s.Receive(readBuffer);
//Console.WriteLine(bc + " Bytes Found");
DumpBytes(readBuffer, bc);
writeBuffer = new byte[] { 0xFF, 0xFC, 0x18, 0xFF, 0xFC, 0x20, 0xFF, 0xFC, 0x23, 0xFF, 0xFC, 0x27, 0xFF, 0xFC, 0x24 };
s.Send(writeBuffer);
readBuffer = new byte[1024];
bc = s.Receive(readBuffer);
//Console.WriteLine(bc + " Bytes Found");
DumpBytes(readBuffer, bc);
writeBuffer = new byte[] { 0xFF, 0xFE, 0x03, 0xFF, 0xFC, 0x01, 0xFF, 0xFC, 0x22, 0xFF, 0xFC, 0x1F, 0xFF, 0xFE, 0x05, 0xFF, 0XFC, 0x21 };
s.Send(writeBuffer);
readBuffer = new byte[1024];
bc = s.Receive(readBuffer);
//Console.WriteLine(bc + " Bytes Found");
DumpBytes(readBuffer, bc);
writeBuffer = new byte[] { 0xFF, 0xFE, 0x01, 0xFF, 0xFC, 0x06, 0xFF, 0xFC, 0x00 };
s.Send(writeBuffer);
readBuffer = new byte[1024];
bc = s.Receive(readBuffer);
//Console.WriteLine(bc + " Bytes Found");
DumpBytes(readBuffer, bc);
writeBuffer = new byte[] { 0xFF, 0xFE, 0x03, 0xFF, 0xFE, 0x01 };
s.Send(writeBuffer);
readBuffer = new byte[1024];
bc = s.Receive(readBuffer);
//Console.WriteLine(bc + " Bytes Found");
DumpBytes(readBuffer, bc);
}
catch
{
Console.WriteLine("Connection to {0} Failed!", address);
}
}
我不想使用最少的 telnet 或任何其他库,我想学习如何完成我已经开始的工作,因为我觉得我已经接近完成它对我的目的有用的程度.
【问题讨论】:
-
您可能想要使用 ReadLine()。然后输入 TELNET 并按回车键。您的应用将等待返回,然后再继续。
-
@jdweng 我最终设置了一个 readBuffer 变量,检查是否有任何字节可供读取,将它们分配给 readBuffer var,获取 readBuffer 长度,最后将十六进制字节数组转换为 ASCii。不太清楚你在回复中的意思。不过谢谢:)