关闭套接字,然后从.net中的同一端口重新打开它

Jas*_*idi 8 .net c# sockets

好吧,我想知道是否有人可以帮助解决我遇到的问题....

我想关闭一个套接字,然后从同一个端口重新运行.这就是我在做的......

开盘:

    UdpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    UdpServerIpEndPoint = new IPEndPoint(IPAddress.Any, 9050);
    UdpEndPoint = (EndPoint)UdpServerIpEndPoint;
    UdpServer.Bind(UdpServerIpEndPoint);
Run Code Online (Sandbox Code Playgroud)

closeing:

        UdpServer.Shutdown(SocketShutdown.Both);
        UdpServer.Disconnect(true);
        UdpServer.Close();
Run Code Online (Sandbox Code Playgroud)

我关闭它之后.并且我尝试使用与上面相同的代码重新连接它,我收到错误:

附加信息:通常只允许使用每个套接字地址(协议/网络地址/端口)

我关闭期间检查异常,但我没有得到任何,我猜他们是正确关闭,所以实际上,是什么原因造成这个问题?请帮忙!

Jas*_*idi 13

我得到了答案....我需要在套接字解除后使用它...

socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress, true);
Run Code Online (Sandbox Code Playgroud)


Pau*_*rry 0

你可以用两种方式来看待这个问题。

  1. 当您处于停止状态时,实际上并不接收,只是在 BeginReceive 中,只需删除/忽略数据

  2. 如果您确实需要重新创建套接字,则不要在服务器上执行断开连接,因为您实际上还没有建立连接。你的断线正在抛出

System.Net.Sockets.SocketException (0x80004005): A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied