public SocketMessageLayer(SimpleSocket context, bool isServer) { this.context = context; this.isServer = isServer; }
/// <summary> /// Initiates a connection to the router. /// </summary> /// <returns></returns> private static Task <SimpleSocket> InitiateConnectionToRouter() { // Let's make sure this run in a different thread (in case some operation are blocking) return(Task.Factory.StartNew(() => { var socketContextTCS = new TaskCompletionSource <SimpleSocket>(); var socketContext = new SimpleSocket(); socketContext.Connected = context => { socketContextTCS.TrySetResult(context); }; try { #if XENKO_PLATFORM_UWP var serverAddress = "127.0.0.1"; #else var serverAddress = Environment.GetEnvironmentVariable("XenkoConnectionRouterRemoteIP") ?? "127.0.0.1"; #endif // If connecting as a client, try once, otherwise try to listen multiple time (in case port is shared) switch (ConnectionMode) { case RouterConnectionMode.Connect: socketContext.StartClient(serverAddress, DefaultPort).Wait(); break; case RouterConnectionMode.Listen: socketContext.StartServer(DefaultListenPort, true, 10).Wait(); break; case RouterConnectionMode.ConnectThenListen: bool clientException = false; try { socketContext.StartClient(serverAddress, DefaultPort).Wait(); } catch (Exception) // Ideally we should filter SocketException, but not available on some platforms (maybe it should be wrapped in a type available on all paltforms?) { clientException = true; } if (clientException) { socketContext.StartServer(DefaultListenPort, true, 10).Wait(); } break; default: throw new ArgumentOutOfRangeException(); } // Connection should happen within 10 seconds, otherwise consider there is no connection router trying to connect back to us if (!socketContextTCS.Task.Wait(TimeSpan.FromSeconds(10))) { throw new SimpleSocketException("Connection router did not connect back to our listen socket"); } return socketContextTCS.Task.Result; } catch (Exception e) { Log.Error($"Could not connect to connection router using mode {ConnectionMode}", e); throw; } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)); }