lidgren / lidgren-network-gen3

Lidgren Network Library
https://groups.google.com/forum/#!forum/lidgren-network-gen3
MIT License
1.19k stars 331 forks source link

NetPeer UniqueIdentifier not unique, LocalEndPoint race condition. #109

Closed hanoixan closed 5 years ago

hanoixan commented 5 years ago

I have a multi-threaded test client that creates many clients to connect to my server at once. When multiple clients are created at the same time, the NetPeer.UniqueIdentifier is often the same, even though the NetPeer.Socket.LocalEndPoint is different when queried after. This of course causes the server to have a fit.

This appears to happen because the NetPeer.Socket.LocalEndPoint is not thread safe, and for a tiny moment there is a race condition where it returns the previous created socket's endpoint.

Currently, there is a local instance lock (m_initializeLock) around the InitializeNetwork() method. I think the naive fix here (without further investigation) would be to protect the BindSocket() method with a static object lock. If I do the same outside the Lidgren API when creating my peers, the race condition ceases to happen. More investigation is needed, but I wanted to put this up for anyone else who is having problems.

Windows 10 Pro, .Net Core 2.0.

lidgren commented 5 years ago

Thanks; added global mutex to socket creation and binding; should solve it