使用TcpClient和TcpListener时会抛出此异常,我有点茫然。第一次运行,然后再次运行,并收到以下异常:
通常允许每个套接字地址(协议/网络地址/端口)仅使用一种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或接口。看来您不需要。
如果所有连接都已关闭,是否不能继续使用相同的地址和端口?
TCP具有一些不直观的行为,导致连接关闭后会挂起一会儿。通过让操作系统为您选择一个新端口,可以缓解该问题。
您可能还想研究并使用Task
一些最佳实践:使用Task.Run
和不处置。没有用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句