Example #1
0
        /// <summary>
        /// Binds to socket and spawns the networking thread
        /// </summary>
        public void Start()
        {
            if (m_status != NetPeerStatus.NotRunning)
            {
                // already running! Just ignore...
                LogWarning("Start() called on already running NetPeer - ignoring.");
                return;
            }

            m_status = NetPeerStatus.Starting;

            // fix network thread name
            if (m_configuration.NetworkThreadName == "Lidgren network thread")
            {
                int pc = Interlocked.Increment(ref s_initializedPeersCount);
                m_configuration.NetworkThreadName = "Lidgren network thread " + pc.ToString();
            }

            InitializeNetwork();

            // start network thread
            m_networkThread              = new Thread(new ThreadStart(NetworkLoop));
            m_networkThread.Name         = m_configuration.NetworkThreadName;
            m_networkThread.IsBackground = true;
            m_networkThread.Start();

            // send upnp discovery
            if (m_upnp != null)
            {
                m_upnp.Discover(this);
            }

            // allow some time for network thread to start up in case they call Connect() or UPnP calls immediately
            NetUtility.Sleep(50);
        }
Example #2
0
        /// <summary>
        /// Binds to socket and spawns the networking thread
        /// </summary>
        public void Start()
        {
            if (m_status != NetPeerStatus.NotRunning || m_status == NetPeerStatus.Starting)
            {
                // already running! Just ignore...
                LogWarning("Start() called on already running NetPeer - ignoring.");
                return;
            }

            m_status = NetPeerStatus.Starting;

            /*
             *          // fix network thread name
             *          if (m_configuration.NetworkThreadName == "Lidgren network thread")
             *          {
             *                  var pc = Interlocked.Increment(ref s_initializedPeersCount);
             *                  m_configuration.NetworkThreadName = "Lidgren network thread " + pc.ToString();
             *          }*/

            InitializeNetwork();

            // send upnp discovery
            m_upnp?.Discover(this);

            // allow some time for network thread to start up in case they call Connect() or UPnP calls immediately
            NetUtility.Sleep(100);
        }
Example #3
0
        /// <summary>
        /// Add a forwarding rule to the router using UPnP
        /// </summary>
        /// <param name="externalPort">The external, WAN facing, port</param>
        /// <param name="description">A description for the port forwarding rule</param>
        /// <param name="internalPort">The port on the client machine to send traffic to</param>
        public bool ForwardPort(int externalPort, string description, int internalPort = 0)
        {
            if (!CheckAvailability())
            {
                return(false);
            }

            IPAddress mask;
            var       client = NetUtility.GetMyAddress(out mask);

            if (client == null)
            {
                return(false);
            }

            if (internalPort == 0)
            {
                internalPort = externalPort;
            }

            try
            {
                SOAPRequest(m_serviceUrl,
                            "<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:" + m_serviceName + ":1\">" +
                            "<NewRemoteHost></NewRemoteHost>" +
                            "<NewExternalPort>" + externalPort.ToString() + "</NewExternalPort>" +
                            "<NewProtocol>" + ProtocolType.Udp.ToString().ToUpper(System.Globalization.CultureInfo.InvariantCulture) + "</NewProtocol>" +
                            "<NewInternalPort>" + internalPort.ToString() + "</NewInternalPort>" +
                            "<NewInternalClient>" + client.ToString() + "</NewInternalClient>" +
                            "<NewEnabled>1</NewEnabled>" +
                            "<NewPortMappingDescription>" + description + "</NewPortMappingDescription>" +
                            "<NewLeaseDuration>0</NewLeaseDuration>" +
                            "</u:AddPortMapping>",
                            "AddPortMapping");

                m_peer.LogDebug("Sent UPnP port forward request");
                NetUtility.Sleep(50);
            }
            catch (Exception ex)
            {
                m_peer.LogWarning("UPnP port forward failed: " + ex.Message);
                return(false);
            }
            return(true);
        }
Example #4
0
        internal void Discover(NetPeer peer)
        {
            string str =
                "M-SEARCH * HTTP/1.1\r\n" +
                "HOST: 239.255.255.250:1900\r\n" +
                "ST:upnp:rootdevice\r\n" +
                "MAN:\"ssdp:discover\"\r\n" +
                "MX:3\r\n\r\n";

            m_status = UPnPStatus.Discovering;

            byte[] arr = System.Text.Encoding.UTF8.GetBytes(str);

            m_peer.LogDebug("Attempting UPnP discovery");
            peer.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
            peer.RawSend(arr, 0, arr.Length, new NetEndPoint(NetUtility.GetBroadcastAddress(), 1900));
            peer.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false);

            // allow some extra time for router to respond
            NetUtility.Sleep(50);

            m_discoveryResponseDeadline = NetTime.Now + 6.0;             // arbitrarily chosen number, router gets 6 seconds to respond
            m_status = UPnPStatus.Discovering;
        }
Example #5
0
        private void ExecutePeerShutdown()
        {
            VerifyNetworkThread();

            LogDebug("Shutting down...");

            // disconnect and make one final heartbeat
            var list = new List <NetConnection>(m_handshakes.Count + m_connections.Count);

            lock (m_connections)
            {
                foreach (var conn in m_connections)
                {
                    if (conn != null)
                    {
                        list.Add(conn);
                    }
                }
            }

            lock (m_handshakes)
            {
                foreach (var hs in m_handshakes.Values)
                {
                    if (hs != null && list.Contains(hs) == false)
                    {
                        list.Add(hs);
                    }
                }
            }

            // shut down connections
            foreach (NetConnection conn in list)
            {
                conn.Shutdown(m_shutdownReason);
            }

            FlushDelayedPackets();

            // one final heartbeat, will send stuff and do disconnect
            Heartbeat();

            NetUtility.Sleep(10);

            lock (m_initializeLock)
            {
                try
                {
                    if (m_socket != null)
                    {
                        try
                        {
                            m_socket.Shutdown(SocketShutdown.Receive);
                        }
                        catch (Exception ex)
                        {
                            LogDebug("Socket.Shutdown exception: " + ex.ToString());
                        }

                        try
                        {
                            m_socket.Close(2);                             // 2 seconds timeout
                        }
                        catch (Exception ex)
                        {
                            LogDebug("Socket.Close exception: " + ex.ToString());
                        }
                    }
                }
                finally
                {
                    m_socket = null;
                    m_status = NetPeerStatus.NotRunning;
                    LogDebug("Shutdown complete");

                    // wake up any threads waiting for server shutdown
                    if (m_messageReceivedEvent != null)
                    {
                        m_messageReceivedEvent.Set();
                    }
                }

                m_lastSocketBind = float.MinValue;
                m_receiveBuffer  = null;
                m_sendBuffer     = null;
                m_unsentUnconnectedMessages.Clear();
                m_connections.Clear();
                m_connectionLookup.Clear();
                m_handshakes.Clear();
            }

            return;
        }
        public void ExecutePeerShutdown()
        {
            Console.WriteLine("Network shutdown enter");
            // disconnect and make one final heartbeat
            var list = new List <NetConnection>(_handshakeManager.Handshakes.Count + m_connections.Count);

            lock (m_connections)
            {
                foreach (var conn in m_connections)
                {
                    if (conn != null)
                    {
                        list.Add(conn);
                    }
                }
            }

            foreach (var hs in _handshakeManager.Handshakes.Values)
            {
                if (hs != null && list.Contains(hs) == false)
                {
                    list.Add(hs);
                }
            }


            // shut down connections
            foreach (NetConnection conn in list)
            {
                conn.Shutdown(m_shutdownReason);
            }

            FlushDelayedPackets();

            // one final heartbeat, will send stuff and do disconnect
            PeerUpdate();

            NetUtility.Sleep(10);

            lock (m_initializeLock)
            {
                try
                {
                    if (m_socket != null)
                    {
                        try
                        {
                            // shutdown socket send and recieve handlers.
                            m_socket.Shutdown(SocketShutdown.Both);
                        }
                        catch (Exception e)
                        {
                            LogDebug(e.ToString());
                        }
                        finally
                        {
                            // close connection, if present
                            m_socket.Close(2);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogDebug("socket shutdown method exception: " + ex.ToString());
                    throw;
                }
                finally
                {
                    NetPeerManager.RemovePeer(this);
                    // wake up any threads waiting for server shutdown
                    m_messageReceivedEvent?.Set();

                    m_lastSocketBind = float.MinValue;
                    m_receiveBuffer  = null;
                    m_sendBuffer     = null;
                    m_unsentUnconnectedMessages?.Clear();
                    m_connections?.Clear();
                    m_connectionLookup?.Clear();
                    _handshakeManager.Handshakes?.Clear();
                    _handshakeManager = null;

                    m_status = NetPeerStatus.NotRunning;
                    LogDebug("Shutdown complete");
                    Console.WriteLine("Shutdown network peer properly");
                }
            }

            return;
        }