繁体   English   中英

我的程序抛出一个现有的连接被远程主机异常强行关闭

[英]My program throws An existing connection was forcibly closed by the remote host exception

我编写了一个小程序,它采用一个 udp 地址并将数据发送到 tcp 地址。 当我在 CMD 中运行程序并获取两个地址时出现错误。

这是代码:

static void Main(string[] args)
{
    IPEndPoint listening = new IPEndPoint(IPAddress.Any, int.Parse(args[0]));
    UdpClient udp = new UdpClient(listening);
    System.Console.WriteLine($"Listening on {listening}");

    var parts = args[1].Split(':');

    IPEndPoint newrelic = new IPEndPoint(IPAddress.Parse(parts[0]), int.Parse(parts[1]));
    TcpClient tcp = new TcpClient();

    bool stop=false;
    Console.CancelKeyPress+=(object? sender, ConsoleCancelEventArgs e) =>
    {
        stop = true;
        tcp.Dispose();
        udp.Close();
        udp.Dispose();
    };
    tcp.Connect(newrelic);
    System.Console.WriteLine($"Connected to {newrelic}");
    var dummy = new IPEndPoint(IPAddress.Any,0);
    while (!stop)
    {
       
            var bytes = udp.Receive(ref dummy);
            if (bytes.Length > 0)
            {
                if (bytes[0] != 0x02)
                {
                    System.Console.WriteLine($"Received {bytes.Length} bytes");
                    var sent = tcp.Client.Send(bytes);
                }
            }
        }
}

我得到的错误是:未处理的异常。 System.Net.Sockets.SocketException (10054):现有连接被远程主机强行关闭。 在 C:\TcpToUdp\Program.cs:line 0 中的 Program.Main(String[] args)

有谁知道为什么?

此错误通常意味着您需要在代码中实现 TLS 1.2。 幸运的是,在您的应用程序尝试到达端点之前,您需要在任何地方添加它。

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM