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

时间:2011-10-30 01:41:27

标签: c# .net sockets

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

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

开口:

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

closeing:

        UdpServer.Shutdown(SocketShutdown.Both);
        UdpServer.Disconnect(true);
        UdpServer.Close();

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

  

附加信息:每个套接字地址只有一种用法   (协议/网络地址/端口)通常是允许的

我在关闭期间检查了异常,但我没有得到任何,我猜他们已经正确关闭,所以实际上,是什么导致了这个问题?请帮忙!

3 个答案:

答案 0 :(得分:13)

我得到了答案.... 我需要在声明socket之后使用它...

socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress, true);

答案 1 :(得分:0)

你可以看看这两种方式。

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

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

  3. 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

答案 2 :(得分:0)

作为参考,如果其他人偶然发现这个问题但是正在寻找UdpClient实现。

int port = 1234;
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
var endPoint = new IPEndPoint(IPAddress.Any, port);
socket.Bind(endPoint);

var updClient = new UdpClient();
updClient.Client = socket;
updClient.Connect(_ipAddress, port);