Пример #1
0
    //-----------------------------------------------------------------------------------------
    private void ManageReliable(IPEndPoint source, NetMessage nm)
    {
        UInt32 id       = nm.PopUInt32();
        int    sourceHC = source.GetHashCode();

        NetMessage tmp = new NetMessage();

        tmp.Push(sourceHC);
        tmp.Push(id);
        UInt64 id64 = tmp.PopUInt64();

        if (alreadyReceived.Contains(id64))
        {
            return;
        }

        tmp.Push(sourceHC);
        tmp.Push(id - 1000);
        UInt64 id641k = tmp.PopUInt64();

        if (alreadyReceived.Contains(id641k))
        {
            alreadyReceived.Remove(id641k);                                  //Only keep 1000 messages in pool
        }
        alreadyReceived.Add(id64);

        tmp = new NetMessage();
        tmp.Push((byte)RU_MessageType.ACK);
        tmp.Push(id);
        _socket.BeginSend(tmp.ToArray(), tmp.GetLength(), source, new AsyncCallback(SentCallback), _socket);

        NetMessage tmp2 = new NetMessage(nm, 5);

        OnMessageReceivedAsync(source, tmp2, true);
    }
Пример #2
0
        public void RunningThread()
        {
            while (Running)
            {
                IPEndPoint remoteIP = new IPEndPoint(IPEndPoint.Address, Port);
                var        data     = UdpClient.Receive(ref remoteIP);
                if (data.Length < 12)
                {
                    continue;
                }
                MemoryStream      ms = new MemoryStream(data);
                CytarStreamReader cr = new CytarStreamReader(ms);
                var ssid             = cr.ReadUInt32();
                // Handle session setup
                if (ssid == 0)
                {
                    ssid = cr.ReadUInt32();
                    // Reset a existed session
                    if (ssid != 0)
                    {
                        if (Sessions.ContainsKey(ssid))
                        {
                            if (Sessions[ssid].RemoteIPAdress == remoteIP.Address)
                            {
                                Sessions[ssid].OnReset(UdpClient, remoteIP);
                            }
                        }
                    }
                    // Start a new session
                    else
                    {
                        ssid = (uint)remoteIP.GetHashCode();
                        UDPSession session = new UDPSession(remoteIP, UdpClient, QosType, ssid);
                        Sessions[ssid] = session;
                        session.StartInternal();
                        Task.Run(() =>
                        {
                            OnSessionSetupCallback?.Invoke(session);
                        });
                        continue;
                    }
                }
                if (!Sessions[ssid].RemoteIPAdress.Equals(remoteIP.Address))
                {
                    continue;
                }
                if (Sessions[ssid].RemotePort != remoteIP.Port)
                {
                    Sessions[ssid].OnReset(UdpClient, remoteIP);
                }
                Sessions[ssid].OnDataReceived(cr.ReadBytes(data.Length - 4));
            }

            foreach (var session in Sessions.Values)
            {
                session.CloseAndWait();
            }
            Sessions = null;
            UdpClient.Dispose();
        }
Пример #3
0
        /// <param name="hostStr">A valid host string that can be resolved by DNS or parsed as an IP address</param>
        /// <param name="port">Port of the end point</param>
        /// <exception cref="ArgumentException"> <paramref name="hostStr"/> contains an invalid IP address</exception>>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     <paramref name="port"/> is less than IPEndPoint.MinPort or port is greater than IPEndPoint.MaxPort</exception>
        public NetEndPoint(string hostStr, int port)
        {
            IPAddress addr = GetFromString(hostStr);

            EndPoint = new IPEndPoint(addr, port);
            _hash    = EndPoint.GetHashCode();
        }
Пример #4
0
 public override int GetHashCode()
 {
     unchecked
     {
         return(((Source != null ? Source.GetHashCode() : 0) * 397) ^ (Destination != null ? Destination.GetHashCode() : 0));
     }
 }
Пример #5
0
        /// <summary>
        /// Stop any udp hole punching in progress towards ep
        /// </summary>
        public void CeaseHolePunching(IPEndPoint ep)
        {
            if (ep == null)
            {
                return;
            }

            int hc = ep.GetHashCode();

            if (m_holePunches != null)
            {
                for (int i = 0; i < m_holePunches.Count;)
                {
                    if (m_holePunches[i] != null && m_holePunches[i].GetHashCode() == hc)
                    {
                        LogVerbose("Ceasing hole punching to " + m_holePunches[i]);
                        m_holePunches.RemoveAt(i);
                    }
                    else
                    {
                        i++;
                    }
                }
                if (m_holePunches.Count < 1)
                {
                    m_holePunches = null;
                }
            }
        }
Пример #6
0
        internal NetEndPoint(IPEndPoint ipEndPoint)
        {
            EndPoint = ipEndPoint;
#if WIN32 && UNSAFE
            SocketAddr = MakeSocketAddr(ipEndPoint);
#endif
            _hash = EndPoint.GetHashCode();
        }
Пример #7
0
 public static void Equals_Invoke_ReturnsExpected(IPEndPoint endPoint, object obj, bool expected)
 {
     Assert.Equal(expected, endPoint.Equals(obj));
     if (obj is IPEndPoint)
     {
         Assert.Equal(expected, endPoint.GetHashCode().Equals(obj.GetHashCode()));
     }
 }
Пример #8
0
        private string Listener_GetIDByEndPoint(IPEndPoint endPoint)
        {
            if (endPoint == null)
            {
                return(null);
            }

            return(endPoint.GetHashCode().ToString());
        }
Пример #9
0
 /// <inheritdoc />
 public override int GetHashCode()
 {
     unchecked
     {
         return(((_name.GetHashCode()) * 397) ^
                _endPoint.GetHashCode() ^
                _localAddress.GetHashCode());
     }
 }
Пример #10
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = Timestamp.GetHashCode();
         hashCode = (hashCode * 397) ^ (Value != null ? Value.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Endpoint != null ? Endpoint.GetHashCode() : 0);
         return(hashCode);
     }
 }
Пример #11
0
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         int hash = 17;
         hash = hash * 23 + source.GetHashCode();
         hash = hash * 23 + pid.GetHashCode();
         return(hash);
     }
 }
Пример #12
0
        /// <param name="hostStr">A valid host string that can be resolved by DNS or parsed as an IP address</param>
        /// <param name="port">Port of the end point</param>
        /// <exception cref="ArgumentException"> <paramref name="hostStr"/> contains an invalid IP address</exception>>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     <paramref name="port"/> is less than IPEndPoint.MinPort or port is greater than IPEndPoint.MaxPort</exception>
        public NetEndPoint(string hostStr, int port)
        {
            IPAddress addr = GetFromString(hostStr);

            EndPoint = new IPEndPoint(addr, port);
#if WIN32 && UNSAFE
            SocketAddr = MakeSocketAddr(EndPoint);
#endif
            _hash = EndPoint.GetHashCode();
        }
Пример #13
0
            public override int GetHashCode()
            {
                //Object
                int result = 1;

                result = Prime * result + ((serverAddress == null) ? 0 : serverAddress.GetHashCode
                                               ());
                result = Prime * result + ((protocol == null) ? 0 : protocol.GetHashCode());
                result = Prime * result + ((rpcKind == null) ? 0 : rpcKind.GetHashCode());
                return(result);
            }
            public override int GetHashCode()
            {
                // Not a great hash but it shouldn't matter in this case.
                var result = 0;

                foreach (byte b in Contents)
                {
                    result = (result * 31) ^ b;
                }
                return(EndPoint.GetHashCode() ^ result);
            }
Пример #15
0
        public static void Equals_Compare_Success()
        {
            IPEndPoint ep  = new IPEndPoint(testIpV41, 500);
            IPEndPoint ep1 = new IPEndPoint(testIpV41, 500);
            IPEndPoint ep2 = new IPEndPoint(testIpV41, 700);
            IPEndPoint ep3 = new IPEndPoint(IPAddress.Parse("192.168.0.9"), 700);

            Assert.False(ep.Equals(null));

            Assert.True(ep.Equals(ep1));
            Assert.True(ep.GetHashCode().Equals(ep1.GetHashCode()));

            Assert.True(ep1.Equals(ep));

            Assert.False(ep.Equals(ep2));
            Assert.False(ep.GetHashCode().Equals(ep2.GetHashCode()));

            Assert.False(ep2.Equals(ep3));
            Assert.False(ep2.GetHashCode().Equals(ep3.GetHashCode()));
        }
Пример #16
0
 private User GetUserByIP(IPEndPoint endpoint)
 {
     foreach (User user in ConnectedUsers)
     {
         if (user.IPAddress.GetHashCode() == endpoint.GetHashCode())
         {
             return(user);
         }
     }
     return(null);
 }
Пример #17
0
 public void Write(IPEndPoint endpoint, Transports transport)
 {
     if (transport != Transports.Ws && transport != Transports.Wss)
     {
         Write(endpoint);
     }
     else
     {
         Write(C.i);
         Write((UInt32)endpoint.GetHashCode());
         Write(C._invalid);
     }
 }
Пример #18
0
            public override int GetHashCode()
            {
                var sh = LocalEP.GetHashCode();
                var dh = RemoteEP.GetHashCode();

                if (sh < dh)
                {
                    return(sh ^ dh);
                }
                else
                {
                    return(dh ^ sh);
                }
            }
Пример #19
0
        public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint, EndPoint destEndPoint)
        {
            var configs = _controller.GetCurrentConfiguration().configs;
            int index;

            if (type == IStrategyCallerType.TCP)
            {
                index = _random.Next();
            }
            else
            {
                index = localIPEndPoint.GetHashCode();
            }
            return(configs[index % configs.Count]);
        }
Пример #20
0
        public UdpServerSession(UInt64 _serverId, uint _conv, Socket _sendSocket, IPEndPoint _remoteIEP, IUdpMsgHandler _handler, long _maxHeartBeatTime)
        {
            serverId    = _serverId;
            handler     = _handler;
            remoteIEP   = _remoteIEP;
            iepHashCode = _remoteIEP.GetHashCode();
            conv        = _conv;

            maxHeartBeatTime      = _maxHeartBeatTime;
            nextCreateSessionTick = clock.ElapsedMilliseconds + KcpDef.KcpMaxVerifyDiffTime;

            kcp = new Kcp(conv, kcpSender);
            kcp.NoDelay(1, 10, 2, 1);
            kcpSender.Init(_sendSocket, kcp, remoteIEP);
            remoteIEP = _remoteIEP;
        }
Пример #21
0
        private string Listener_GetIDByEndPoint(IPEndPoint endPoint)
        {
            try
            {
                if (endPoint == null)
                {
                    return(null);
                }

                return(endPoint.GetHashCode().ToString());
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("获取UID时出错", ex.Message, ex.StackTrace);
                return(StringUtil.UniqueID());
            }
        }
Пример #22
0
        public IPEndPoint GetServieByLoadBalane(List <FlowControlEndPoint> lbEndPoints, IPEndPoint clientIp, LoadBalanceType type = LoadBalanceType.IPHash, ServiceConfigureInfo configure = null)
        {
            var result = default(FlowControlEndPoint);

            if (lbEndPoints != null && lbEndPoints.Any())
            {
                //若没有客户端IP则默认调用随机
                if (clientIp == null && type == LoadBalanceType.IPHash)
                {
                    type = LoadBalanceType.Random;
                }
                switch (type)
                {
                //随机
                case LoadBalanceType.Random:
                    result = lbEndPoints.OrderBy(x => Guid.NewGuid()).FirstOrDefault();
                    break;

                //轮询
                case LoadBalanceType.Polling:
                    result = TargetIp == null?lbEndPoints.FirstOrDefault() :
                                 lbEndPoints.Any(x => x.HashSort > TargetIpSortInex) ?
                                 lbEndPoints.First(x => x.HashSort > TargetIpSortInex) :
                                 lbEndPoints.First();

                    TargetIp         = result.GetEndPoint();
                    TargetIpSortInex = result.HashSort;
                    break;

                //IP哈希
                case LoadBalanceType.IPHash:
                    result = lbEndPoints[Math.Abs(clientIp.GetHashCode()) % lbEndPoints.Count];
                    break;

                //最小连接
                case LoadBalanceType.MinConnections:
                    result = lbEndPoints.OrderBy(x => x.ConnectCount).FirstOrDefault();
                    break;
                }
            }
            if (configure != null)
            {
                configure.ChangeConnectCount(result.GetEndPoint(), true);
            }
            return(result.GetEndPoint());
        }
Пример #23
0
    public List <byte> Serialize()
    {
        List <byte> data = new List <byte>();

        data.AddRange(BitConverter.GetBytes(endPoint.GetHashCode())); // Client id
        data.Add((byte)TransformCount);                               // Transform Count
        if (instance == null)
        {
            Debug.LogWarning("Null instance in Serialize");
            return(new List <byte>());
        }
        foreach (Transform t in instance.transform /*transforms*/)
        {
            //data.AddRange(t.Value.Serialize());
            data.AddRange(new Trans(t.position, t.rotation, t.name).Serialize());
        }
        return(data);
    }
Пример #24
0
        private NetConnection FindConnection(IPEndPoint endpoint)
        {
            NetConnection retval;

            if (m_connectionsLookUpTable.TryGetValue(endpoint.GetHashCode(), out retval))
            {
                return(retval);
            }
            return(null);

            /*
             * for (int i = 0; i < Connections.Length; i++)
             * {
             *      if (Connections[i] != null && Connections[i].Status != NetConnectionStatus.Disconnected && Connections[i].RemoteEndpoint.Equals(endpoint))
             *              return Connections[i];
             * }
             * return null;
             */
        }
Пример #25
0
 public override int GetHashCode()
 {
     unchecked
     {
         int result = InstanceId.GetHashCode();
         result = (result * 397) ^ State.GetHashCode();
         result = (result * 397) ^ IsAlive.GetHashCode();
         result = (result * 397) ^ InternalTcpEndPoint.GetHashCode();
         result = (result * 397) ^ (InternalSecureTcpEndPoint != null ? InternalSecureTcpEndPoint.GetHashCode() : 0);
         result = (result * 397) ^ ExternalTcpEndPoint.GetHashCode();
         result = (result * 397) ^ (ExternalSecureTcpEndPoint != null ? ExternalSecureTcpEndPoint.GetHashCode() : 0);
         result = (result * 397) ^ InternalHttpEndPoint.GetHashCode();
         result = (result * 397) ^ ExternalHttpEndPoint.GetHashCode();
         result = (result * 397) ^ EpochPosition.GetHashCode();
         result = (result * 397) ^ EpochNumber.GetHashCode();
         result = (result * 397) ^ EpochId.GetHashCode();
         result = (result * 397) ^ NodePriority;
         return(result);
     }
 }
Пример #26
0
        internal NetConnection AddConnection(IPEndPoint remoteEndpoint, int remoteClockOffset)
        {
            // find empty slot
            for (int i = 0; i < Connections.Length; i++)
            {
                if (Connections[i] == null)
                {
                    NetConnection conn = new NetConnection(this, remoteEndpoint);

                    conn.RemoteClockOffset = remoteClockOffset;
                    Log.Verbose("Initializing remote clock offset to " + remoteClockOffset + " ms");

                    conn.m_firstSentHandshake = NetTime.Now;
                    conn.m_lastSentHandshake  = conn.m_firstSentHandshake;

                    int           hash = remoteEndpoint.GetHashCode();
                    NetConnection existingConn;
                    if (m_connectionsLookUpTable.TryGetValue(hash, out existingConn))
                    {
                        if (existingConn.Status != NetConnectionStatus.Disconnected)
                        {
                            throw new NetException("Ack thphth; Connections lookup hash value taken!");
                        }

                        // disconnected; just remove it
                        RemoveConnection(existingConn);
                    }

                    Connections[i] = conn;

                    m_connectionsLookUpTable[hash] = conn;

                    conn.SetStatus(NetConnectionStatus.Connecting, "Connecting from " + remoteEndpoint);
                    return(conn);
                }
            }

            Log.Warning("Failed to add new connection!");
            return(null);
        }
Пример #27
0
        public void NetHelper_IPEndPoint_Hash()
        {
            // Verify that the hash related methods in IPEndPoint
            // actually work.

            IPEndPoint ep1, ep2;

            ep1 = new IPEndPoint(IPAddress.Parse("10.0.0.1"), 10);
            ep2 = new IPEndPoint(IPAddress.Parse("10.0.0.1"), 10);
            Assert.AreEqual(ep1.GetHashCode(), ep2.GetHashCode());
            Assert.IsTrue(ep1.Equals(ep2));

            ep1 = new IPEndPoint(IPAddress.Parse("10.0.0.1"), 10);
            ep2 = new IPEndPoint(IPAddress.Parse("10.0.0.2"), 10);
            Assert.AreNotEqual(ep1.GetHashCode(), ep2.GetHashCode());
            Assert.IsFalse(ep1.Equals(ep2));

            ep1 = new IPEndPoint(IPAddress.Parse("10.0.0.1"), 10);
            ep2 = new IPEndPoint(IPAddress.Parse("10.0.0.1"), 11);
            Assert.AreNotEqual(ep1.GetHashCode(), ep2.GetHashCode());
            Assert.IsFalse(ep1.Equals(ep2));
        }
Пример #28
0
        public static void Equals_Compare_Success()
        {
            IPEndPoint ep = new IPEndPoint(testIpV41, 500);
            IPEndPoint ep1 = new IPEndPoint(testIpV41, 500);
            IPEndPoint ep2 = new IPEndPoint(testIpV41, 700);
            IPEndPoint ep3 = new IPEndPoint(IPAddress.Parse("192.168.0.9"), 700);

            Assert.False(ep.Equals(null));

            Assert.True(ep.Equals(ep1));
            Assert.True(ep.GetHashCode().Equals(ep1.GetHashCode()));

            Assert.True(ep1.Equals(ep));

            Assert.False(ep.Equals(ep2));
            Assert.False(ep.GetHashCode().Equals(ep2.GetHashCode()));

            Assert.False(ep2.Equals(ep3));
            Assert.False(ep2.GetHashCode().Equals(ep3.GetHashCode()));
        }
Пример #29
0
 public override int GetHashCode()
 {
     return(mIPEndPoint.GetHashCode());
 }
Пример #30
0
        private void InitializeNetwork()
        {
            lock (m_initializeLock)
            {
                m_configuration.Lock();

                if (m_status == NetPeerStatus.Running)
                {
                    return;
                }

                if (m_configuration.m_enableUPnP)
                {
                    m_upnp = new NetUPnP(this);
                }

                InitializePools();

                m_releasedIncomingMessages.Clear();
                m_unsentUnconnectedMessages.Clear();
                m_handshakes.Clear();

                // bind to socket
                IPEndPoint iep = null;

                iep = new IPEndPoint(m_configuration.LocalAddress, m_configuration.Port);
                EndPoint ep = (EndPoint)iep;

                m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                m_socket.ReceiveBufferSize = m_configuration.ReceiveBufferSize;
                m_socket.SendBufferSize    = m_configuration.SendBufferSize;
                m_socket.Blocking          = false;
                m_socket.Bind(ep);

                try
                {
                    const uint IOC_IN            = 0x80000000;
                    const uint IOC_VENDOR        = 0x18000000;
                    uint       SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
                    m_socket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
                }
                catch
                {
                    // ignore; SIO_UDP_CONNRESET not supported on this platform
                }

                IPEndPoint boundEp = m_socket.LocalEndPoint as IPEndPoint;
                LogDebug("Socket bound to " + boundEp + ": " + m_socket.IsBound);
                m_listenPort = boundEp.Port;

                m_receiveBuffer            = new byte[m_configuration.ReceiveBufferSize];
                m_sendBuffer               = new byte[m_configuration.SendBufferSize];
                m_readHelperMessage        = new NetIncomingMessage(NetIncomingMessageType.Error);
                m_readHelperMessage.m_data = m_receiveBuffer;

                byte[] macBytes = new byte[8];
                NetRandom.Instance.NextBytes(macBytes);

#if IS_MAC_AVAILABLE
                try
                {
                    System.Net.NetworkInformation.PhysicalAddress pa = NetUtility.GetMacAddress();
                    if (pa != null)
                    {
                        macBytes = pa.GetAddressBytes();
                        LogVerbose("Mac address is " + NetUtility.ToHexString(macBytes));
                    }
                    else
                    {
                        LogWarning("Failed to get Mac address");
                    }
                }
                catch (NotSupportedException)
                {
                    // not supported; lets just keep the random bytes set above
                }
#endif
                byte[] epBytes  = BitConverter.GetBytes(boundEp.GetHashCode());
                byte[] combined = new byte[epBytes.Length + macBytes.Length];
                Array.Copy(epBytes, 0, combined, 0, epBytes.Length);
                Array.Copy(macBytes, 0, combined, epBytes.Length, macBytes.Length);
                m_uniqueIdentifier = BitConverter.ToInt64(SHA1.Create().ComputeHash(combined), 0);

                m_status = NetPeerStatus.Running;
            }
        }
Пример #31
0
        void ProcessIncomingConnection(IAsyncResult ar)
        {
            TcpListener listener  = (TcpListener)ar.AsyncState;
            TcpClient   client    = listener.EndAcceptTcpClient(ar);
            SslStream   sslStream = new SslStream(client.GetStream(), false);

            //Console.WriteLine("SOCKET TYPE " + client.Connected);

            try
            {
                sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, true);
                sslStream.ReadTimeout  = 1000;
                sslStream.WriteTimeout = 1000;

                // Show certs info
                //DisplayCertificateInformation(sslStream);

                // remote ip address
                //Console.Write(((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());
                IPEndPoint newclient = (IPEndPoint)client.Client.RemoteEndPoint;
                Console.WriteLine("Connected with {0} at port {1} and Serialize {2} HASH### {3}", newclient.Address, newclient.Port, newclient.Serialize().ToString(), newclient.GetHashCode());
            }
            catch (Exception ee)
            {
                Console.WriteLine("Client without sslSocket " + ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());
                sslStream.Close();
                client.Client.Close();
            }
            ThreadPool.QueueUserWorkItem(ProcessIncomingData, sslStream);
            tcpClientConnected.Set();
        }