gpt4 book ai didi

c# - TcpClient 套接字 - 每个套接字地址异常的唯一用法

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:17 25 4
gpt4 key购买 nike

当使用 TcpClient 和 TcpListener 时抛出这个异常,我有点不知所措。它第一次工作,然后我再次运行它,我得到以下异常:

每个套接字地址(协议(protocol)/网络地址/端口)通常只允许使用一次 127.0.0.1:8086

我已检查以确保关闭所有打开的连接。我已经尝试在 TcpClient 上手动调用 close 以及使用 IDisposable using 模式,但仍然遇到同样的问题。

这是代码,如果您将其复制粘贴到 Visual Studio 中,它应该会运行(前提是您已添加以下 using 语句)

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

internal class Program
{
private static void tcpClientConnection()
{
Console.WriteLine("Ready");
Console.ReadKey();

IPAddress address = IPAddress.Parse("127.0.0.1");

using (TcpClient client = new TcpClient(new IPEndPoint(address, 8087)))
{
client.Connect(new IPEndPoint(address, 8086));

using (NetworkStream ns = client.GetStream())
{
ns.Write(System.Text.Encoding.ASCII.GetBytes("Hello"), 0, "Hello".Length);
ns.Flush();
}

Console.WriteLine("Closing client");
}
}

internal static void Main(string[] args)
{
IPAddress address = IPAddress.Parse("127.0.0.1");

TcpListener server = new TcpListener(new IPEndPoint(address, 8086));
server.Start();

using (Task task2 = new Task(tcpClientConnection))
{
task2.Start();

using (TcpClient client = server.AcceptTcpClient())
{
using (NetworkStream ns = client.GetStream())
{
using (MemoryStream ms = new MemoryStream())
{
ns.CopyTo(ms);
byte[] data = ms.ToArray();

Console.WriteLine(System.Text.Encoding.ASCII.GetString(data));
}
}
}

Console.WriteLine("Server stop");
Console.ReadKey();

server.Stop();
}

Console.WriteLine("END");
Console.ReadKey();

}
}

请注意,我查看了类似问题中提供的解决方案,但没能看出问题所在...

最佳答案

对于 TcpClient,不要指定本地端点。我认为这解决了问题,无论如何你都不应该这样做,因为它什么也做不了。 为传出连接指定本地端点会使操作系统选择适当的可用值。通常,99.9% 的程序都在这样做。

一些程序需要指定本地端点以便只监听特定的 IP 或接口(interface)。看来你不需要那个。

If all the connections are being closed, should it not be ok to continue using the same address and port?

TCP 有一些不直观的行为会导致连接在关闭后停留一段时间。通过让操作系统为您选择一个新的端口,问题就会得到缓解。

您可能还想查看 Task 的用法并获得一些最佳实践:使用 Task.Run 并且不要处置。这是毫无意义的。

关于c# - TcpClient 套接字 - 每个套接字地址异常的唯一用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34118639/

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