gpt4 book ai didi

c# - 使用 .net 的 Telnet 连接

转载 作者:太空狗 更新时间:2023-10-30 00:36:04 25 4
gpt4 key购买 nike

我们办公室目前使用 telnet 查询外部服务器。过程是这样的。

  1. 连接 - telnet opent 128........ 25000
  2. 查询 - 我们粘贴查询然后点击 alt + 019
  3. 响应 - 我们在 telnet 窗口中收到文本形式的响应

所以我尝试使用 C# 应用程序自动执行此查询。我的代码如下

首先是连接。 (没有异常(exception))

    SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
String szIPSelected = txtIPAddress.Text;
String szPort = txtPort.Text;
int alPort = System.Convert.ToInt16(szPort, 10);

System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(szIPSelected);
System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, alPort);
SocketClient.Connect(remoteEndPoint);

然后我发送查询(没有异常(exception))

    string data ="some query";
byte[] byData = System.Text.Encoding.ASCII.GetBytes(data);
SocketClient.Send(byData);

然后我尝试接收响应

    byte[] buffer = new byte[10];
Receive(SocketClient, buffer, 0, buffer.Length, 10000);
string str = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
txtDataRx.Text = str;

public static void Receive(Socket socket, byte[] buffer, int offset, int size, int timeout)
{
int startTickCount = Environment.TickCount;
int received = 0; // how many bytes is already received
do
{
if (Environment.TickCount > startTickCount + timeout)
throw new Exception("Timeout.");
try
{
received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.WouldBlock ||
ex.SocketErrorCode == SocketError.IOPending ||
ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
{
// socket buffer is probably empty, wait and try again
Thread.Sleep(30);
}
else
throw ex; // any serious error occurr
}
} while (received < size);
}

每次我尝试接收响应时,如果打开 telnet 并发送相同的查询,我会立即收到响应“一个现有的连接已被远程主机强行关闭”

有什么想法或建议吗?

最佳答案

根据你我之间的评论交流,你似乎需要在查询末尾附加 Ascii 代码 19 (0x13)。

关于c# - 使用 .net 的 Telnet 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2906475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com