ERROR: "Usually only one use of each socket address is allowed"

3

Before they say that "the port is already being used, try another one", I have received this response several times, and changing the port simply does not work.

Well, I'm developing a game that uses Socket via UDP to transmit data over the network, but every time I instantiate the UdpClient class it gives me the following error:

"Usually only one use of each socket address (protocol / network address / port) is allowed"

Here's my code:

        public void OnInit(Component.InitContext context)
    {
        if (context == InitContext.Activate)
        {
            servers = new List<ServerInfo>();
            renderers = new List<GameObject>();
            end = false;
            bool tryagain = true;
            while (tryagain)
            {
                try
                {
                    listener = new UdpClient(port);
                    tryagain = false;
                }
                catch (Exception e)
                {
                    tryagain = true;
                    listener.Close();
                    Log.Game.Write(e.Message);
                }
            }
            ips = new List<string>();
            Thread thread = new Thread(new ThreadStart(run));
            thread.Start();
        }
    }

I made a loop when instantiating my listener, but it stays in the loop forever, the port variable is currently 11022, but I have already tested it with 11000, 11001, 11002, 11003, 1234, 7654, 9999, 123 between others that I do not remember.

I also tried accessing the netstat command by cmd to check which ports are being used, before running the program, none of the ports mentioned appear, but after running the program and the error appears, the port then appears in netstat, and then of a time some.

I have also been instructed to change a registry called ReservedPorts in the HKEY_LOCAL_MACHINE / SYSTEM / CurrentControlSet / services / Tcpip / Parameters path, adding my port, but it does not appear that this registry exists

In fact this error only happens sometimes, when I change the computer or folder, the first few times the program can access the port normally, then it seems that it can not anymore. Maybe I'm not closing the door right, but my code has that part:

 public void OnShutdown(Component.ShutdownContext context)
    {
        end = true;
        listener.Close();

    }

So the door theoretically should be closed when the program is finished, right?

What am I doing wrong?

    
asked by anonymous 18.02.2016 / 13:41

1 answer

0

There is a listener linking to port port in exclusive mode. To indicate shared binding, initialize your UdpClient as follows:

listener udpServer = new UdpClient();

listener.Client.SetSocketOption(
    SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

listener.Client.Bind(localpt);
    
18.02.2016 / 14:26