public Dialog_ModSync_Window() { MSLog.Log("New window", MSLog.Level.All); try { CurrSyncState = CurrentSyncState.RequestStarted; ClientInternetConnectivity = InternetConnectivity.Unchecked; closeOnClickedOutside = false; FetchRelevantMods(); string userRequest = NetworkManager.GenerateServerRequestString(_relevantMods); _userRequestStr = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(userRequest)); NetworkManager.CheckForInternetConnectionAsync( this.ClientInternetConnectivity, (InternetConnectivity clientInternetConnectivity) => { this.ClientInternetConnectivity = clientInternetConnectivity; this.OnNetworkConnectionTestCompleted(); }); } catch (Exception e) { MSLog.Log("ERROR:", MSLog.Level.All); MSLog.Log(e.Message, MSLog.Level.All); } }
/// <summary> /// Algorithm to check internet connection. /// [Broken] [Level -1] The state of the system when internet has been declared unavailable. /// [Level 0] If the system reports no cable/wifi connection, there is no connection /// [Level 1] If the system reports cable/wifi, we can assume there is a connection for now /// [Level 2] The system reported cable/wifi, be believed it, but let's check by pinging Google /// [Level 3] If the system still reports cable/wifi, but a Google ping failed to work, we'll hope for the best and give it one more shot /// [Level 4] Failed twice or more, so there is no connection because something's broken. /// </summary> /// <returns></returns> private bool checkInternet() { if (conn_test_counter == -1) { //We have a problem. Major check til it works. conn_test_counter = InternetConnectivity.strongInternetConnectionTest() ? 0 : -1; return(conn_test_counter == 0); } if (InternetConnectivity.IsConnectionAvailable()) { ++conn_test_counter; if (conn_test_counter == 4) { conn_test_counter = InternetConnectivity.strongInternetConnectionTest() ? 0 : conn_test_counter + 1; Console.WriteLine("[Level 2] Working Internet Connection - Timer Check"); return(true); } else if (conn_test_counter > 5) { conn_test_counter = InternetConnectivity.strongInternetConnectionTest() ? 0 : conn_test_counter + 1; if (conn_test_counter > 7) { conn_test_counter = -1; Console.WriteLine("[Level 4] No Internet Connection - Timer Check"); return(false); } else { //Let's give it one more shot Console.WriteLine("[Level 3] Working Internet Connection - Timer Check"); return(true); } } else { Console.WriteLine("[Level 1] Working Internet Connection - Timer Check"); return(true); } } else { Console.WriteLine("[Level 0] No Connection - Timer Check"); conn_test_counter = -1; return(false); } }
public Dialog_CheckMods() { #if DIALOG_CHECK_MODS Log.Warning("Begin Dialog_CheckMods()"); #endif try { this.Status = InternetConnectivity.Unchecked; closeOnClickedOutside = false; this.FindModsToSync(); #if TRACE && DIALOG_CHECK_MODS Log.Message(" ModsToSync Count: " + ((modsToSync == null) ? "<null>" : modsToSync.Count.ToString())); #endif if (this.modsToSync != null && this.modsToSync.Count > 0) { #if TRACE && DIALOG_CHECK_MODS Log.Message(" Check Internet Connection"); #endif RestUtil.CheckForInternetConnectionAsync((bool result) => { #if TRACE && DIALOG_CHECK_MODS Log.Warning("Callback: " + result); #endif this.Status = (result) ? InternetConnectivity.Online : InternetConnectivity.Offline; if (this.Status == InternetConnectivity.Online) { this.Resync(); } }); } } #if TRACE && DIALOG_CHECK_MODS catch (Exception e) { Log.Error("Exception: " + e.GetType().Name + " " + e.Message); } #else catch { } #endif #if DIALOG_CHECK_MODS Log.Warning("End Dialog_CheckMods()"); #endif }
private void parseCommand_host(string parameters) { IModel model = controller.Model; IView view = controller.View; Regex parametersRegex = new Regex(@"^(?<1>\d+)\s*(?<2>(?:copy)?)\s*$", RegexOptions.Singleline); Match parametersMatch = parametersRegex.Match(parameters); if (parametersMatch.Success) { if (model.NetworkClient.Status != NetworkStatus.Disconnected) { view.Prompter.AddTextToHistory(0xFFFF0000, Resources.DisconnectFirst); } else { int port = int.Parse(parametersMatch.Groups[1].Value); bool copyToClipboard = (parametersMatch.Groups[2].Value == "copy"); // prepare server process using (Process serverProcess = new Process()) { serverProcess.StartInfo.FileName = Assembly.GetExecutingAssembly().Location; serverProcess.StartInfo.Arguments = "-s " + port.ToString(); serverProcess.StartInfo.UseShellExecute = false; serverProcess.StartInfo.RedirectStandardOutput = true; // launch server process serverProcess.Start(); // wait for the server to start string serverOutput = serverProcess.StandardOutput.ReadLine(); if (serverOutput.StartsWith("Server started")) { // connect to server model.IsHosting = true; model.StateChangeSequenceNumber = 0; model.NetworkClient.Connect("localhost", port); Regex publicAddressRegex = new Regex(@"^Server started (?<1>[0-4])/(?<2>[^/]+)/(?<3>[^/]+)", RegexOptions.Singleline); Match publicAddressMatch = publicAddressRegex.Match(serverOutput); if (publicAddressMatch.Success) { InternetConnectivity connectivity = (InternetConnectivity)Enum.Parse(typeof(InternetConnectivity), publicAddressMatch.Groups[1].Value); string publicIpAddress = publicAddressMatch.Groups[2].Value; string publicPort = publicAddressMatch.Groups[3].Value; if (connectivity != InternetConnectivity.Full) { FirewallDialog firewallDialog = null; switch (connectivity) { case InternetConnectivity.Unknown: firewallDialog = new FirewallDialog(controller, Connectivity.Limited); break; case InternetConnectivity.None: firewallDialog = new FirewallDialog(controller, Connectivity.NoInternet); break; case InternetConnectivity.NoEgress: firewallDialog = new FirewallDialog(controller, Connectivity.NoEgress); break; case InternetConnectivity.NoIngress: firewallDialog = new FirewallDialog(controller, Connectivity.NoIngress); break; } controller.DialogState.Dialog = firewallDialog; controller.State = controller.DialogState; controller.View.ShowDialog(firewallDialog); } if (connectivity != InternetConnectivity.None) { view.Prompter.AddTextToHistory(0xFFFF0000, (publicPort != "?" ? Resources.ServerListeningNatTraversalEnabled : Resources.ServerListeningNatTraversalDisabled), publicIpAddress, (publicPort != "?" ? publicPort : port.ToString())); if (copyToClipboard) { Clipboard.SetText(string.Format(Resources.ConnectionData, publicIpAddress, (publicPort != "?" ? publicPort : port.ToString()))); view.Prompter.AddTextToHistory(0xFFFF0000, Resources.ConnectionDataCopiedToClipboard); } } else { view.Prompter.AddTextToHistory(0xFFFF0000, Resources.NoInternetConnection); } } else { view.Prompter.AddTextToHistory(0xFFFF0000, Resources.NoInternetConnection); } Settings.Default.HostPort = port; } else { // something went wrong if (serverOutput == "Invalid Device Address") { view.Prompter.AddTextToHistory(0xFFFF0000, Resources.CantStartServerInvalidDeviceAddress, port); FirewallDialog firewallDialog = new FirewallDialog(controller, Connectivity.PortInUse); controller.DialogState.Dialog = firewallDialog; controller.State = controller.DialogState; controller.View.ShowDialog(firewallDialog); } else { view.Prompter.AddTextToHistory(0xFFFF0000, Resources.CantStartServer, serverOutput); } } } } } else { view.Prompter.AddTextToHistory(0xFFFF0000, Resources.InvalidParameters, "host", "host <port_number> [copy]"); } }
/// <summary>Begin a new game as a host.</summary> /// <param name="mode">Server codec and mixing policy.</param> /// <param name="port">IP port that will listen.</param> public void Start(VoiceServerMode mode, int port) { uncompressJobsPending = new ManualResetEvent(false); try { ApplicationDescription description = new ApplicationDescription(); description.GuidApplication = new Guid("{920BAF09-A06C-47d8-BCE0-21B30D0C3586}"); description.MaxPlayers = 0; // unlimited description.SessionName = "ZunTzu"; description.Flags = Microsoft.DirectX.DirectPlay.SessionFlags.ClientServer | Microsoft.DirectX.DirectPlay.SessionFlags.FastSigned | Microsoft.DirectX.DirectPlay.SessionFlags.NoDpnServer | Microsoft.DirectX.DirectPlay.SessionFlags.NoEnumerations; using (Address address = new Address()) { address.ServiceProvider = Address.ServiceProviderTcpIp; address.AddComponent(Address.KeyPort, port); server.Host(description, address); } if (System.Environment.OSVersion.Version.Major < 6) // not Vista? // launch a voice session { voiceServer = new Microsoft.DirectX.DirectPlay.Voice.Server(server); SessionDescription desc = new SessionDescription(); desc.SessionType = SessionType.Fowarding; // (mode == VoiceServerMode.ForwardingAdpcm || mode == VoiceServerMode.ForwardingGsm ? SessionType.Fowarding : SessionType.Mixing); desc.BufferQuality = BufferQuality.Default; desc.GuidCompressionType = (mode == VoiceServerMode.ForwardingAdpcm || mode == VoiceServerMode.MixingAdpcm ? CompressionGuid.AdPcm : CompressionGuid.Gsm); desc.BufferAggressiveness = BufferAggressiveness.Default; desc.Flags = Microsoft.DirectX.DirectPlay.Voice.SessionFlags.NoHostMigration; //desc.Flags = Microsoft.DirectX.DirectPlay.Voice.SessionFlags.ServerControlTarget; voiceServer.StartSession(desc); } // allow NAT traversal (3 trials) InternetConnectivity connectivity = InternetConnectivity.Unknown; for (int trial = 0; (natTraversalSession == null || !natTraversalSession.Enabled) && trial < 3; ++trial) { natTraversalSession = NatResolver.EnableNatTraversal(port); } string fallbackPublicIpAddress = null; if (natTraversalSession.Enabled) { // notify the parent process via the standard output connectivity = InternetConnectivity.Full; } else { // fallback: discover public IP through HTTP try { // Start a synchronous request. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://www.zuntzu.com/hostfallback.php"); request.UserAgent = "ZunTzu"; request.Timeout = 10000; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes("id=" + natTraversalSession.SessionId.ToString("N")); request.ContentLength = bytes.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Length); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK) { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream)) { string responseContent = reader.ReadToEnd(); Regex ipAddressRegex = new Regex(@"^(?<1>[012])(?<2>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", RegexOptions.Singleline); Match ipAddressMatch = ipAddressRegex.Match(responseContent); if (ipAddressMatch.Success) { switch (ipAddressMatch.Groups[1].Value) { case "0": connectivity = InternetConnectivity.Unknown; break; case "1": connectivity = InternetConnectivity.NoEgress; break; case "2": connectivity = InternetConnectivity.NoIngress; break; } fallbackPublicIpAddress = ipAddressMatch.Groups[2].Value; } } } } else { throw new WebException(); } } } catch (Exception) { // fallback: query a public web site to check Internet connectivity try { // Start a synchronous request. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://www.google.com/"); request.Timeout = 10000; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { throw new WebException(); } } } catch (Exception) { connectivity = InternetConnectivity.None; } } } // notify the parent process via the standard output switch (connectivity) { case InternetConnectivity.Unknown: case InternetConnectivity.None: Console.Out.WriteLine("Server started {0}/?/?", (int)connectivity); break; case InternetConnectivity.NoEgress: case InternetConnectivity.NoIngress: Console.Out.WriteLine("Server started {0}/{1}/?", (int)connectivity, fallbackPublicIpAddress); break; case InternetConnectivity.Full: Console.Out.WriteLine("Server started {0}/{1}/{2}", (int)connectivity, natTraversalSession.PublicIpAddress, natTraversalSession.PublicPort); break; } } catch (InvalidDeviceAddressException) { // notify the parent process via the standard output Console.Out.WriteLine("Invalid Device Address"); } catch (Exception e) { // notify the parent process via the standard output Console.Out.WriteLine(e.Message); } Console.Out.Flush(); processVideoFrames(); }