Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Editor tool Socket

Discussion in 'Editor & General Support' started by hugeandy, Apr 29, 2021.

  1. hugeandy

    hugeandy

    Joined:
    Nov 2, 2016
    Posts:
    130
    Hi all,

    We have an external tool which communicates with unity via a Socket. We have a problem with keeping this Socket open over the entire lifetime of an editor session by dealing with recompiles.

    We open the Socket when Unity opens/after a script recompiles using the [DidReloadScripts] attribute. We have also tried using [InitializeOnLoadMethod].
    Code (CSharp):
    1. [DidReloadScripts]
    2. private static void StartServer() {
    3.     var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    4.    var bindEndPoint = new IPEndPoint(IPAddress.Any, Port);
    5.    socket.Bind(bindEndPoint);
    6. }

    The problem we run into is that sometimes after scripts have recompiled, the Socket constructor throws due to the port being in use:
    SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted.

    I have tried lots of different methods to Close and Dispose the Socket before scripts are recompiled, and they all work just some of the time. Maybe it will work for 10 recompiles but then on the 11th, it'll throw when creating the Socket.

    Currently we use this to close the Socket:
    Code (CSharp):
    1.  
    2. EditorApplication.update += OnEditorUpdate;
    3.  
    4. private static void OnEditorUpdate() {
    5.    if (EditorApplication.isCompiling) {
    6.       if (socket != null) {
    7.          StopServer();
    8.       }
    9.    }
    10. }
    Code (CSharp):
    1. private static void StopServer() {          
    2.     if (socket != null) {
    3.        socket.Close();
    4.        socket.Dispose();
    5.        socket = null;
    6.    }
    7. }
    We have also tried to subscribe to the
    AssemblyReloadEvents.beforeAssemblyReload
    event to stop the server and I'm sure other methods which I can't remember.

    What is the "proper" way to do this, to ensure that our Socket is always disposed of properly, so that when we recreate it the port is available?

    Cheers,
    Andy
     
  2. hugeandy

    hugeandy

    Joined:
    Nov 2, 2016
    Posts:
    130
  3. GeleArtur

    GeleArtur

    Joined:
    May 13, 2018
    Posts:
    1
    Same issue. Have you found a solution?
     
  4. hugeandy

    hugeandy

    Joined:
    Nov 2, 2016
    Posts:
    130
    @GeleArtur no, I stopped trying to get this to work before coming up with a solution. There must be a way which works, and if you find it please update here!