有没有办法让UDP .net套接字在套接字关闭时释放绑定端口?

时间:2012-02-25 22:42:00

标签: c# windows sockets windows-7 udp

对于这个问题,我正在运行Windows 7 64位,.net framework 3.5

我真正想知道的是

  1. 有没有办法取消绑定/释放已绑定的端口?
  2. 当我设置socketoption重用地址时,我能够绑定到端口,但我从未使用该地址/端口接收数据?
  3. 我正在查看使用netstat -apd udp绑定的端口

    我正在使用的测试代码如下,通常我收到一个数据包后不会关闭端口。

    EndPoint endpoint = new IPEndPoint(state.IPAddress, state.Port);
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,ProtocolType.Udp);
    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);                    
    socket.Bind(endpoint);
    
    
    ReadStateObject stateObject = new ReadStateObject();
    stateObject.socket = socket;
    stateObject.Port = state.Port;
    stateObject.IPAddress = state.IPAddress;
    stateObject.BurstDataReceivedEvent = state.BurstDataReceivedEvent;
    stateObject.shutdownRequested = state.StopRequestedEvent;
    socket.BeginReceiveFrom(stateObject.buffer,
                            0,
                            stateObject.buffer.Length,
                            SocketFlags.None, // Was 0 which is likely the same enumeration but this is clearer
                            ref endpoint,
                            new AsyncCallback(BurstUdpListener.SocketBeginReceiveAsyncCallback),
                             stateObject);
    
    // wait for read to complete... or the thread to be asked to stop
    while (stateObject.readFinished.WaitOne(100, false) == false)
    {
        // has this thread been requested to stop? if so, cancel the pending read
        if (state.StopRequestedEvent.WaitOne(1, false) == true)
        {
            stop = true;
            break;
         }
     }
    
     socket.Shutdown(SocketShutdown.Both);
     socket.Close();
     socket = null;
    
    
    
        private static void SocketBeginReceiveAsyncCallback(IAsyncResult ar)
        {
    
                if (ar.IsCompleted)
                {
                    ReadStateObject state = ar.AsyncState as ReadStateObject;
                    if (state != null)
                    {
                        if (state.shutdownRequested.WaitOne(1, false))
                            return;
                        EndPoint endpoint = new IPEndPoint(state.IPAddress, state.Port);
                        int bytesReceived = state.socket.EndReceiveFrom(ar, ref endpoint); // for some reason throws error here on changes to settings
                        if (state.BurstDataReceivedEvent != null)
                        {
                            state.BurstDataReceivedEvent(null, new BurstDataReceivedEventArgs(state.buffer, bytesReceived));
                        }
                        state.readFinished.Set();
                    }
    
             }            
    
     }
    

1 个答案:

答案 0 :(得分:1)

调用close()时应该释放端口,因此听起来没有调用close()或者没有成功。

删除shutdown()调用,因为它实际上不适用于UDP。

检查close()的错误返回,以确保它被调用并且返回成功。