Keep network socket open during play mode recompile

I have custom networking code using the C# Tcp socket classes. Works great. The only problem comes when I edit a script during play mode – when any script is recompiled during play, my socket connection is lost, my C# TcpClient object becomes invalid, and my game crashes.

Is there any way to keep a socket open between recompiles? (Unity’s internal networking classes do it, so they should have exposed some way for us to do it, too, since they claim to fully support custom network solutions… there shouldn’t be anything a custom network solution can’t theoretically do!)

And if there really isn’t a way to keep a socket open (and a reference to that socket handy, so I can communicate with it), is there a way to stop the Automatic-Recompile-During-Playmode feature? Currently, editing a script during play mode will lock up my machine as it generates thousands of errors related to the now-missing socket.

Thanks for any insights you might have here!

I know that this is an old question, but it has left me stumped for months.

The route that I’m going is to serialize the IP endpoint and handshake information from the connection and reinitialize the socket on Awake of my network manager ScriptableObject. The server code simply needs to keep a List of client endpoints and their identity from the client handshake and it should not have a problem. Just recreate the socket on Awake. With UDP, it is rather trivial since connections are artificial anyway.

This, in theory, should work for TCP as well. You’ll just need to prepare for two methods of connection handshake: “New Connection” and “Resume Connection”. The client will need to know to automatically reconnect to a server that drops it using the “Resume Connection”. And the server will need to be prepared to accept clients back that drop suddenly, and cache any information about to be sent incase it fails.

Also relevant is the Serialization help article that shows how to custom serialize data. You could use OnBeforeSerialize and OnAfterDeserialize to serialize dictionaries or any custom network information that you require.

is your Socket object a static object?
Does it have any static fields of methods?
This can cause the problem