为什么会为TcpClient(IPEndPoint)而不是TcpClient(String,Int32)抛出套接字使用异常? [英] Why would a socket in use exception be thrown for TcpClient(IPEndPoint) but not TcpClient(String, Int32)?

查看:61
本文介绍了为什么会为TcpClient(IPEndPoint)而不是TcpClient(String,Int32)抛出套接字使用异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会为我的代码中有一个与我一起使用的侦听器(ip为:: 1,端口为12345)

I have in my code a listener that I use with (ip is ::1, port is 12345)

listener = new TcpListener(ip, port); //create listener
listener.Start(); //start listener
//now code will wait at the while loop until someone connects.
while (listener.Pending()) { System.Threading.Thread.Sleep(1000); } //check for pending connections every second.
client = listener.AcceptTcpClient(); //when incoming connection is found accept it.

请注意,代码位于 Task监听器中Task = Task.Run(()=> {});

在另一个任务中,我有以下内容

in another task I have the following

//client = new TcpClient(new IPEndPoint(ip, port)); //does not work
client = new TcpClient("localhost", port); //localhost resolves to ::1

那是怎么回事?有什么区别?我对本地主机解析为:: 1错吗?如果仍然无法解决问题,那么我的程序又该如何回显自身?

So what's the deal? What is the difference? Am I wrong about localhost resolving to ::1? If it doesn't resolve to that then how can my program echo back on itself?

我会在此期间尝试获取更多信息.

I will try to get more information in the meantime.

异常详细信息:

System.Net.Sockets.SocketException was unhandled
ErrorCode=10048
HResult=-2147467259
Message=Only one usage of each socket address (protocol/network address/port) is normally permitted
NativeErrorCode=10048
Source=System
StackTrace:
     at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
     at System.Net.Sockets.Socket.Bind(EndPoint localEP)
     at System.Net.Sockets.TcpClient..ctor(IPEndPoint localEP)
     at ConsoleApplication1.Program.Connector(IPAddress[] ips, Int32 port)

推荐答案

我的代码:

client = new TcpClient(new IPEndPoint(ip, port)); 

使用 local IP地址绑定 local 端口以供以后使用.

Binds the local port with the local IP address for later use.

一旦知道了这一点,便可以将代码更改为以下内容,并且可以按照我的预期进行工作:

Once knowing this I was able to change my code to the following and it works how I intended it to:

client = new TcpClient(new IPEndPoint(localIp, localPort)); //sets up how we are going to be connecting.
client.Connect(remoteIp, remotePort); //does the real connecting.

来源:https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient%28v=vs.110%29.aspx

这篇关于为什么会为TcpClient(IPEndPoint)而不是TcpClient(String,Int32)抛出套接字使用异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆