public void LogonPlayer(string server, string playername, string password) { // Try the connect now this.Initialize(); // Make sure dplay is setup properly host.AddComponent(Address.KeyHostname, server); ApplicationDescription desc = new ApplicationDescription(); desc.GuidApplication = MessengerShared.applicationGuid; try { // Connect to this server client.Connect(desc, host, device, null, 0); // Now we will sit and wait in a loop for our connect complete event to fire while (!hConnect.WaitOne(0, false)) { // Don't kill the CPU, allow other things to happen while we wait Application.DoEvents(); } if (gConnected) // We connected, try to log on now { gServer = server; LogonPlayer(playername, password); } } catch { MessageBox.Show("This server could not be contacted. Please check the server name and try again.", "Server not found.", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
//--------------------------------------------------------------------- #endregion // DirectPlay Object Initializations /// <summary> /// Host a new DirectPlay session. /// </summary> public void HostSession() { // Update the UI m_Form.SessionStatusLabel.Text = "Connecting..."; m_Form.Update(); // Create an application description ApplicationDescription AppDesc = new ApplicationDescription(); AppDesc.GuidApplication = m_AppGuid; AppDesc.Flags = SessionFlags.NoDpnServer; // Set the port number on which to host m_LocalAddress.AddComponent("port", DefaultPort); try { // Host a new session m_Peer.Host(AppDesc, // Application description m_LocalAddress); // Local device address m_Connection = ConnectionType.Hosting; } catch (Exception ex) { m_Form.ShowException(ex, "Host", true); m_Form.Dispose(); return; } }
public void AddComponent_Int(int value) { var address = new Address(); address.AddComponent(Address.KeyPort, value); address.GetComponentInteger(Address.KeyPort).Should().Be(value); }
/// <summary> /// Find all sessions at the given host address /// </summary> /// <param name="hostname">IP address or hostname to search</param> /// <param name="port">Remote port to search</param> public void EnumerateSessions(string hostname, int port) { // Set the desired search options Address HostAddress = new Address(); HostAddress.ServiceProvider = Address.ServiceProviderTcpIp; if (hostname.Length > 0) { HostAddress.AddComponent("hostname", hostname); } if (port > 0) { HostAddress.AddComponent("port", port); } ApplicationDescription AppDesc = new ApplicationDescription(); AppDesc.GuidApplication = m_AppGuid; // Find all sessions hosted at the given address. When a session is // found, DirectPlay calls our FindHostResponse delegate. Since we're // passing in the "Sync" flag, Connect will block until the search // timeout has expired. try { m_Peer.FindHosts(AppDesc, // Application description HostAddress, // Host address m_LocalAddress, // Local device address null, // Enumeration data 0, // Enumeration count (using default) 0, // Retry interval (using default) 0, // Timeout (using default) FindHostsFlags.Sync); // Flags } catch (Exception ex) { m_Form.ShowException(ex, "FindHosts", true); m_Form.Dispose(); return; } }
/// <summary> /// Host a new DirectPlay session. /// </summary> public void HostSession() { // Get desired hosting options HostDialog dialog = new HostDialog(); dialog.LocalPort = DefaultPort; if (DialogResult.Cancel == dialog.ShowDialog()) { return; } // Update the UI m_Form.SessionStatusLabel.Text = "Connecting..."; m_Form.Update(); // Store host dialog choices m_SessionName = dialog.SessionName; // Add the port number if (dialog.LocalPort > 0) { m_LocalAddress.AddComponent("port", dialog.LocalPort); } // Create an application description ApplicationDescription AppDesc = new ApplicationDescription(); AppDesc.GuidApplication = m_AppGuid; AppDesc.SessionName = m_SessionName; AppDesc.Flags = SessionFlags.NoDpnServer; // Enable host migration if (dialog.IsHostMigrationEnabled) { AppDesc.Flags |= SessionFlags.MigrateHost; } try { // Host a new session m_Peer.Host(AppDesc, // Application description m_LocalAddress); // Local device address m_Connection = ConnectionType.Hosting; } catch (Exception ex) { m_Form.ShowException(ex, "Host", true); m_Form.Dispose(); return; } }
/// <summary> /// We are ready to create a session. Ensure the data is valid /// then create the session /// </summary> private void btnOK_Click(object sender, System.EventArgs e) { ApplicationDescription dpApp; if ((txtSession.Text == null) || (txtSession.Text == "")) { MessageBox.Show(this,"Please enter a session name before clicking OK.","No sessionname",MessageBoxButtons.OK,MessageBoxIcon.Information); return; } Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\DirectX\\SDK\\csDPlay"); if (regKey != null) { regKey.SetValue("DirectPlaySessionName", txtSession.Text); if (migrateHostCheckBox.Checked) regKey.SetValue("DirectPlayMigrateHost",1); else regKey.SetValue("DirectPlayMigrateHost",0); if (fastSignedRadio.Checked) regKey.SetValue("DirectPlaySessionSigning","Fast"); else if (fullSignedRadio.Checked) regKey.SetValue("DirectPlaySessionSigning","Full"); else regKey.SetValue("DirectPlaySessionSigning","Disabled"); regKey.Close(); } dpApp = new ApplicationDescription(); dpApp.GuidApplication = connectionWizard.ApplicationGuid; dpApp.SessionName = txtSession.Text; dpApp.Flags = 0; if (migrateHostCheckBox.Checked) dpApp.Flags |= SessionFlags.MigrateHost; if (!useDPNSVRCheckBox.Checked) dpApp.Flags |= SessionFlags.NoDpnServer; if (fastSignedRadio.Checked) dpApp.Flags |= SessionFlags.FastSigned; else if (fullSignedRadio.Checked) dpApp.Flags |= SessionFlags.FullSigned; // Specify the port number if available if (ConnectWizard.ProviderRequiresPort(deviceAddress.ServiceProvider)) { if (Port > 0) deviceAddress.AddComponent(Address.KeyPort, Port); } connectionWizard.SetUserInfo(); // Host a game on deviceAddress as described by dpApp // HostFlags.OkToQueryForAddressing allows DirectPlay to prompt the user // using a dialog box for any device address information that is missing peer.Host(dpApp,deviceAddress,HostFlags.OkToQueryForAddressing); this.DialogResult = DialogResult.OK; }
public bool InitializeClient(string name) { // Create our client object ThinClient = new Client(); NewDataList = new List <DataPacket>(); bool connectionSuccess = true; // Check to see if we can create a TCP/IP connection if (!IsServiceProviderValid(Address.ServiceProviderTcpIp)) { connectionSuccess = false; } // Create a new address for our local machine Address deviceAddress = new Address(); deviceAddress.ServiceProvider = Address.ServiceProviderTcpIp; // Create a new address for our host machine Address hostaddress = new Address(); hostaddress.ServiceProvider = Address.ServiceProviderTcpIp; hostaddress.AddComponent(Address.KeyPort, ServerInfo.DataPort); // Find out about the newer standard!! // Set our name PlayerInformation info = new PlayerInformation(); info.Name = name; ThinClient.SetClientInformation(info, SyncFlags.ClientInformation); // Set up an application description ApplicationDescription desc = new ApplicationDescription(); desc.GuidApplication = ServerInfo.ApplicationGuid; //Attach Event handlers ThinClient.ConnectComplete += new ConnectCompleteEventHandler(OnConnectComplete); ThinClient.FindHostResponse += new FindHostResponseEventHandler(OnFindHost); ThinClient.Receive += new ReceiveEventHandler(OnDataReceive); ThinClient.SessionTerminated += new SessionTerminatedEventHandler(OnSessionTerminate); try { // Search for a server //This will trigger the FindHostResponse event if a server is up and running ThinClient.FindHosts(desc, hostaddress, deviceAddress, null, 0, 0, 0, FindHostsFlags.None); } catch { connectionSuccess = false; } return(connectionSuccess); }
public void EqualsTest() { var address1 = new Address(); address1.AddComponent(Address.KeyProvider, Address.ServiceProviderTcpIp); address1.AddComponent(Address.KeyHostname, "localhost"); address1.AddComponent(Address.KeyPort, 2310); var address2 = new Address(); address2.AddComponent(Address.KeyPort, 2310); address2.AddComponent(Address.KeyHostname, "localhost"); address2.AddComponent(Address.KeyProvider, Address.ServiceProviderTcpIp); var address3 = new Address(); address3.AddComponent(Address.KeyHostname, "localhost"); address3.AddComponent(Address.KeyPort, 2310); address3.AddComponent(Address.KeyProvider, Address.ServiceProviderTcpIp); address1.Equals(address2).Should().BeFalse(); address1.Equals(address3).Should().BeTrue(); address2.Equals(address3).Should().BeFalse(); }
private void btnStart_Click(object sender, System.EventArgs e) { serverStarted = !serverStarted; if (serverStarted) // Do the opposite since we just changed it a second ago { // Set up the application description ApplicationDescription desc = new ApplicationDescription(); desc.GuidApplication = MessengerShared.applicationGuid; desc.MaxPlayers = maxUsers; desc.SessionName = "DxMessengerServer"; desc.Flags = SessionFlags.ClientServer | SessionFlags.NoDpnServer; // Create a new address that will reside on tcpip and listen only on our port Address add = new Address(); add.ServiceProvider = Address.ServiceProviderTcpIp; add.AddComponent(Address.KeyPort, MessengerShared.DefaultPort); // Now we can start our server server = new Server(); // Add our event handlers server.PlayerDestroyed += new PlayerDestroyedEventHandler(this.DestroyPlayerMsg); server.Receive += new ReceiveEventHandler(this.DataReceivedMsg); // Host this session try { server.Host(desc, add); } catch (InvalidDeviceAddressException) { MessageBox.Show("Another instance of this server with the same application Guid was found. This instance will now exit."); return; } this.btnStart.Text = "Stop Server"; UpdateText(); } else { this.btnStart.Text = "Start Server"; lstUsers.Items.Clear(); numPlayers = 0; server.Dispose(); server = null; //Update our text, the server should not be running UpdateText(); } Initialized = true; }
//A true return signals that the server is up and running public bool InitializeServer() { NewPlayerList = new List <string>(); NewDataList = new List <DataPacket>(); DcdPlayerList = new List <string>(); PrivateServer = new Server(); bool setupSuccess = true; // Check to see if we can create a TCP/IP connection if (!IsServiceProviderValid(Address.ServiceProviderTcpIp)) { setupSuccess = false; } else { // Create a new address for our local machine Address deviceAddress = new Address(); deviceAddress.ServiceProvider = Address.ServiceProviderTcpIp; deviceAddress.AddComponent(Address.KeyPort, ServerInfo.DataPort); // Set up an application description ApplicationDescription desc = new ApplicationDescription(); desc.SessionName = "MDX Book Server Session"; desc.GuidApplication = ServerInfo.ApplicationGuid; desc.Flags = SessionFlags.ClientServer | SessionFlags.NoDpnServer; try { // Host a new session on the Server PrivateServer.Host(desc, deviceAddress); } catch { setupSuccess = false; } } //Attach all handlers PrivateServer.PlayerCreated += new PlayerCreatedEventHandler(OnPlayerCreated); PrivateServer.Receive += new ReceiveEventHandler(OnDataReceive); PrivateServer.PlayerDestroyed += new PlayerDestroyedEventHandler(OnPlayerDestroyed); return(setupSuccess); }
public void InitializeServer() { connection = new Server(); connection.PlayerCreated += new PlayerCreatedEventHandler(OnPlayerCreated); connection.PlayerDestroyed += new PlayerDestroyedEventHandler(OnPlayerDestroyed); connection.Receive += new ReceiveEventHandler(OnDataReceive); connection.Disposing += new EventHandler(OnDisposing); if (!IServiceProviderValid(Address.ServiceProviderTcpIp)) { MessageBox.Show("Невозможно создать TCP/IP службу поддержки", "Выход", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); } Address deviceAddress = null; deviceAddress = new Address(); deviceAddress.ServiceProvider = Address.ServiceProviderTcpIp; deviceAddress.AddComponent(Address.KeyPort, SharedCode.DataPort); ApplicationDescription desc = new ApplicationDescription(); desc.SessionName = textBox1.Text; desc.MaxPlayers = 2; desc.GuidApplication = SharedCode.ApplicationGuid; desc.Flags = SessionFlags.ClientServer | SessionFlags.NoDpnServer; try { connection.Host(desc, deviceAddress); statusCreated(true); MessageBox.Show("Сессия создана", "", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { MessageBox.Show("Невозможно создать сессию", "", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public void Initialize() { if (client != null) { client.Dispose(); } client = new Client(); device = new Address(); host = new Address(); // Set the device to use TCP/IP device.ServiceProvider = Address.ServiceProviderTcpIp; // The host is running on tcp/ip on the port listed in shared host.ServiceProvider = Address.ServiceProviderTcpIp; host.AddComponent(Address.KeyPort, MessengerShared.DefaultPort); // Set up our event handlers client.ConnectComplete += new ConnectCompleteEventHandler(this.ConnectComplete); client.Receive += new ReceiveEventHandler(this.DataReceived); client.SessionTerminated += new SessionTerminatedEventHandler(this.SessionLost); }
/// <summary> /// We either want to start or stop searching /// </summary> private void btnSearch_Click(object sender, System.EventArgs e) { if (!isSearching) { if( hostAddress != null ) hostAddress.Dispose(); hostAddress = new Address(); hostAddress.ServiceProvider = deviceAddress.ServiceProvider; // See if we should prompt the user for the remote address if (ConnectWizard.ProviderRequiresPort(hostAddress.ServiceProvider)) { AddressForm addressDialog = new AddressForm(connectionWizard.DefaultPort); addressDialog.ShowDialog(this); // If the user cancelled the address form, abort the search if (addressDialog.DialogResult != DialogResult.OK) return; // If a port was specified, add the component if (addressDialog.Hostname != "") hostAddress.AddComponent(Address.KeyHostname, addressDialog.Hostname); // If a hostname was specified, add the component if (addressDialog.Port > 0) hostAddress.AddComponent(Address.KeyPort, addressDialog.Port); } //Time to enum our hosts ApplicationDescription desc = new ApplicationDescription(); desc.GuidApplication = connectionWizard.ApplicationGuid; // If the user was not already asked for address information, DirectPlay // should prompt with native UI FindHostsFlags flags = 0; if (!ConnectWizard.ProviderRequiresPort(deviceAddress.ServiceProvider)) flags = FindHostsFlags.OkToQueryForAddressing; peer.FindHosts(desc,hostAddress,deviceAddress,null,Timeout.Infinite,0,Timeout.Infinite, flags, out findHostHandle); isSearching = true; btnCreate.Enabled = false; btnSearch.Text = "Stop Search"; } else { btnSearch.Text = "Stopping..."; btnSearch.Enabled = false; if (findHostHandle != 0) peer.CancelAsyncOperation(findHostHandle); } }
/// <summary> /// We either want to start or stop searching /// </summary> private void btnSearch_Click(object sender, System.EventArgs e) { if (!isSearching) { if (hostAddress != null) { hostAddress.Dispose(); } hostAddress = new Address(); hostAddress.ServiceProvider = deviceAddress.ServiceProvider; // See if we should prompt the user for the remote address if (ConnectWizard.ProviderRequiresPort(hostAddress.ServiceProvider)) { AddressForm addressDialog = new AddressForm(connectionWizard.DefaultPort); addressDialog.ShowDialog(this); // If the user cancelled the address form, abort the search if (addressDialog.DialogResult != DialogResult.OK) { return; } // If a port was specified, add the component if (addressDialog.Hostname != "") { hostAddress.AddComponent(Address.KeyHostname, addressDialog.Hostname); } // If a hostname was specified, add the component if (addressDialog.Port > 0) { hostAddress.AddComponent(Address.KeyPort, addressDialog.Port); } } //Time to enum our hosts ApplicationDescription desc = new ApplicationDescription(); desc.GuidApplication = connectionWizard.ApplicationGuid; // If the user was not already asked for address information, DirectPlay // should prompt with native UI FindHostsFlags flags = 0; if (!ConnectWizard.ProviderRequiresPort(deviceAddress.ServiceProvider)) { flags = FindHostsFlags.OkToQueryForAddressing; } peer.FindHosts(desc, hostAddress, deviceAddress, null, Timeout.Infinite, 0, Timeout.Infinite, flags, out findHostHandle); isSearching = true; btnCreate.Enabled = false; btnSearch.Text = "Stop Search"; } else { btnSearch.Text = "Stopping..."; btnSearch.Enabled = false; if (findHostHandle != 0) { peer.CancelAsyncOperation(findHostHandle); } } }
/// <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(); }
/// <summary>Connect to a server.</summary> /// <param name="serverName">IP address or hostname of the server.</param> /// <param name="serverPort">IP port on which the server is listening.</param> /// <remarks>The first client to connect becomes the hosting player.</remarks> public void Connect(string serverName, int serverPort) { Debug.Assert(status == NetworkStatus.Disconnected); serverIsOnSameComputer = (serverName == "localhost"); outboundVideoFrameHistory = new OutboundVideoFrameHistory(); inboundVideoFrameHistories = new Dictionary <int, InboundVideoFrameHistory>(); soundBuffers = new Dictionary <int, Buffer3D>(); client = new Microsoft.DirectX.DirectPlay.Client(InitializeFlags.DisableParameterValidation); client.ConnectComplete += new ConnectCompleteEventHandler(onConnectComplete); client.Receive += new ReceiveEventHandler(onReceive); client.SessionTerminated += new SessionTerminatedEventHandler(onSessionTerminated); status = NetworkStatus.Connecting; // trigger NAT traversal EnabledAddresses enabledAddresses = NatResolver.TestNatTraversal(serverName, serverPort); ApplicationDescription description = new ApplicationDescription(); description.GuidApplication = new Guid("{920BAF09-A06C-47d8-BCE0-21B30D0C3586}"); // try first using the host's public address using (Address hostAddress = (enabledAddresses == null ? new Address(serverName, serverPort) : new Address(enabledAddresses.HostPublicAddress, enabledAddresses.HostPublicPort))) { hostAddress.ServiceProvider = Address.ServiceProviderTcpIp; using (Address device = new Address()) { device.ServiceProvider = Address.ServiceProviderTcpIp; device.AddComponent(Address.KeyTraversalMode, Address.TraversalModeNone); if (enabledAddresses != null) { device.AddComponent(Address.KeyPort, enabledAddresses.ClientPrivatePort); } using (NetworkPacket packet = new NetworkPacket()) { try { client.Connect(description, hostAddress, device, packet, 0); } catch (Exception e) { status = NetworkStatus.Disconnected; ConnectionFailureCause cause = (e is NoConnectionException ? ConnectionFailureCause.NoConnection : (e is NotHostException ? ConnectionFailureCause.NotHost : (e is SessionFullException ? ConnectionFailureCause.SessionFull : ConnectionFailureCause.Other))); // try again using the host's private address if (enabledAddresses != null) { using (Address hostPrivateAddress = new Address(enabledAddresses.HostPrivateAddress, enabledAddresses.HostPrivatePort)) { try { client.Connect(description, hostAddress, device, packet, 0); } catch { NetworkMessage message = new NetworkMessage(0, (byte)ReservedMessageType.ConnectionFailed, new byte[1] { (byte)cause }); lock (networkMessages) { networkMessages.Enqueue(message); } return; } } } else { NetworkMessage message = new NetworkMessage(0, (byte)ReservedMessageType.ConnectionFailed, new byte[1] { (byte)cause }); lock (networkMessages) { networkMessages.Enqueue(message); } return; } } } } } // launch a timer to monitor timeout timeoutTimer = new System.Threading.Timer(onTimeout, client, 4000, 0); }