以下代码尽管显然关闭了UDP套接字,但仍然无法重新连接到同一个地址/端口.
这些是我使用的类变量:
Thread t_listener;
List<string> XSensAvailablePorts;
private volatile bool stopT_listener = false;
volatile UdpClient listener;
IPEndPoint groupEP;
Run Code Online (Sandbox Code Playgroud)
我用一个处理Socket连接和监听的方法创建并启动一个新线程:
private void startSocketButton_Click(object sender, RoutedEventArgs e)
{
stopT_listener = false;
closeSocketButton.IsEnabled = true;
startSocketButton.IsEnabled = false;
t_listener = new Thread(UDPListener);
t_listener.Name = "UDPListenerThread";
t_listener.Start();
}
Run Code Online (Sandbox Code Playgroud)
该方法如下(我使用超时Receive
,以便在套接字上没有发送任何内容并且正在发出时不会阻止它Stop
):
private void UDPListener()
{
int numberOfPorts = XSensAvailablePorts.Count();
int currAttempt = 0;
int currPort = 0;
bool successfullAttempt = false;
while (!successfullAttempt && currAttempt < numberOfPorts)
{
try
{
currPort = Int32.Parse(XSensAvailablePorts[currAttempt]); …
Run Code Online (Sandbox Code Playgroud)