You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#(.NET Framework 4.6.2)实现Telnet服务器同步通信?

.NET Framework 4.6.2 同步Telnet通信实现(过滤发送指令)

直接用原生Socket实现同步Telnet通信,同时处理返回内容中包含发送指令的问题,代码简洁且符合同步编程要求:

核心实现代码

using System;
using System.Net.Sockets;
using System.Text;

public class TelnetSyncClient
{
    private Socket _tcpSocket;
    private readonly string _serverHost;
    private readonly int _serverPort;

    public TelnetSyncClient(string host, int port)
    {
        _serverHost = host;
        _serverPort = port;
    }

    public string ExecuteCommand(string command)
    {
        // 初始化并建立同步连接
        if (_tcpSocket == null || !_tcpSocket.Connected)
        {
            _tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // 可添加超时设置
            _tcpSocket.ReceiveTimeout = 5000;
            _tcpSocket.Connect(_serverHost, _serverPort);
        }

        // 发送指令(多数Telnet服务器需换行符触发执行,根据实际情况调整为\r\n或\n)
        byte[] commandBytes = Encoding.ASCII.GetBytes($"{command}\r\n");
        _tcpSocket.Send(commandBytes);

        // 读取服务器响应
        byte[] receiveBuffer = new byte[1024];
        int receivedLength = _tcpSocket.Receive(receiveBuffer);
        string rawResponse = Encoding.ASCII.GetString(receiveBuffer, 0, receivedLength);

        // 过滤掉返回内容中的发送指令
        // 拆分响应行,跳过第一行(发送的指令),拼接实际响应
        string[] responseSegments = rawResponse.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
        string cleanResponse = responseSegments.Length > 1 
            ? string.Join(Environment.NewLine, responseSegments[1..]) 
            : rawResponse;

        // 清理多余控制字符并返回
        return cleanResponse.Replace("\r", "").Trim();
    }

    public void CloseConnection()
    {
        _tcpSocket?.Shutdown(SocketShutdown.Both);
        _tcpSocket?.Close();
        _tcpSocket = null;
    }
}

使用示例

// 实例化客户端并执行指令
var telnetClient = new TelnetSyncClient("your-server-ip", 23);
try
{
    string status = telnetClient.ExecuteCommand("Status");
    Console.WriteLine(status); // 输出: Online
}
catch (SocketException ex)
{
    // 处理连接/通信异常
    Console.WriteLine($"通信错误: {ex.Message}");
}
finally
{
    telnetClient.CloseConnection();
}

关键说明

  • 同步通信:全程使用Socket的同步方法(Connect、Send、Receive),满足底层SDK的同步要求。
  • 响应过滤:通过拆分响应行跳过发送的指令,解决返回内容包含指令的问题;如果服务器返回格式不同,可调整拆分的分隔符。
  • 编码适配:默认用ASCII编码,若服务器使用UTF-8,替换为Encoding.UTF8即可。
  • 超时控制:可通过ReceiveTimeout设置读取超时,避免无限等待。

内容的提问来源于stack exchange,提问作者Hem Bhagat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 06:06:17