3

I am using Lidgren in Monogame. There is a possibility that a player would want to host a game, then exits the lobby, and wants to host again. However, when I do this in my code, the following exception is raised: System.Net.Sockets.SocketException: 'Only one usage of each socket address (protocol/network address/port) is normally permitted'

Relevant code:

// initializing the server
NetPeerConfiguration _config = new NetPeerConfiguration("some app id");
// code to enable certain messages.
_server = new NetServer(_config);
_server.Start();

// cleaning up the server instance
_server.Shutdown("server shutdown");
_server = null;

The code crashes at _server.Start() with binding the socket.(m_socket.Bind()).

How can I clean the server/socket up so that I can create a new instance of the server a second time around?

Danahi
  • 98
  • 1
  • 11
  • Is anyone else encountering this issue? There were 40 views, and (at this point) two upvotes.. – Danahi Jul 24 '20 at 09:58
  • What I think is happening, is that you are recreating the server every time the player wants to host, so it doesn't remember that you already have bound ports. It is then trying to bind the port again, so it fails. What I think you should try is only call `new NetServer` once, like in the constructor - and remove `_server = null`. Then *only* use `_server.Start();` and `_server.Shutdown("...")` to flip the server on and off. – Junior Jul 25 '20 at 09:54
  • Let me think if this help to solve your issue how to handle more than one request at a time in parallel by using threads. – Nadeem Taj Jul 30 '20 at 19:49

1 Answers1

0

The cause of this is an improper shutdown of the previous server's instance meaning the port is still in use by that instance. Seems to have been a bug, the internal cleanup didn't work properly https://github.com/lidgren/lidgren-network-gen3/issues/94 https://github.com/lidgren/lidgren-network-gen3/issues/94#issuecomment-369561026 however it was fixed so be sure to have the latest version of lidgren-network https://github.com/RevoluPowered/lidgren-network/tree/feature/socket-overhaul

you can use _server.Socket.Close(); just to be sure the socket closes before starting another server or instance.

Code Demon
  • 1,256
  • 1
  • 9
  • 15