How can I change a UdpClient port after I established it a first time (Only one usage of each socket address is normally permitted)

StackOverflow https://stackoverflow.com/questions/19367313

  •  30-06-2022
  •  | 
  •  

質問

So i'm trying to make something that allows the user to change connections..(disregarded the IP code because that part isn't erroring.. just the port)

    private readonly UdpClient _udpListener;
    private IPEndPoint _listeningEndPoint;

    public FeedbackListener( int feedbackPort )
    {
        _listeningEndPoint = new IPEndPoint( IPAddress.Any, _feedbackPort );            
        _udpListener = new UdpClient( _listeningEndPoint );
    }

so say the user connects once:

public FeedbackListener _feedback;

_feedback = new FeedbackListener(Convert.ToInt32(port));

and they try to disconnect and reconnect with a DIFFERENT port:

//_udpListener.Close();  tried this, just turns into another about accessing a disposed object
_feedback = new FeedbackListener(Convert.ToInt32(port));

i get this error: Only one usage of each socket address is normally permitted... so is there any way i can successfully change the port without getting this error?

役に立ちましたか?

解決

You need to keep only one instance of IPEndPoint and only update the Port when you want to instantiate a new UdpClient

Something like:

private static IPEndPoint _listeningEndPoint = null;

public FeedbackListener( int feedbackPort )
{
    if ( _listeningEndPoint == null)
    {
       _listeningEndPoint =  new IPEndPoint( IPAddress.Any, feedbackport);
    }
    else
    {
        _listeningEndPoint.Port = feedbackport;
    } 
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top