Ejemplo n.º 1
0
        public void OnReceivePacket(DatagramPacket datagramPacket)
        {
            byte[] dpData = datagramPacket.Data;

            int sType          = PacketCheck.CheckSType(datagramPacket);
            int remoteClientId = BitConverter.ToInt32(dpData, 9);

            if (sType == PacketType.PingPacket)
            {
                PingPacket pingPacket = new PingPacket(datagramPacket);
                SendPingPacket2(pingPacket.PingId, datagramPacket.Host, datagramPacket.Port);
                CurrentSpeed = pingPacket.DownloadSpeed * 1024;
            }
            else if (sType == PacketType.PingPacket2)
            {
                PingPacket2 pingPacket2 = new PingPacket2(datagramPacket);
                LastReceivePingTime = DateTimeExtensions.CurrentTimeMillis();
                long?t = PingTable[pingPacket2.PingId];
                if (t != null)
                {
                    PingDelay = (int)(DateTimeExtensions.CurrentTimeMillis() - t);
                    string protocal = "udp";
                    Console.WriteLine("delay_" + protocal + " " + PingDelay + "ms " + datagramPacket.Host + ":" + datagramPacket.Port);
                }
            }
        }
Ejemplo n.º 2
0
        void ScanClientControl()
        {
            long current = DateTimeExtensions.CurrentTimeMillis();

            foreach (KeyValuePair <int, ClientControl> ccItem in ClientTable)
            {
                ClientControl clientControl = ccItem.Value;
                if (clientControl != null)
                {
                    if (current - clientControl.LastReceivePingTime < ReceivePingTimeout &&
                        current - clientControl.LastReceivePingTime > SendPingInterval)
                    {
                        clientControl.SendPingPacket();
                    }
                }
                else
                {
                    //Timtout
                    Console.WriteLine("Timeout and close client: "
                                      + clientControl.DstHost + ":" + clientControl.DstPort
                                      + " " + DateTime.Now.ToString());

                    lock (SynClientTable)
                    {
                        clientControl.Close();
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public void verifyToken(LoginUser loginUser)
        {
            long expireTime  = loginUser.expireTime;
            long currentTime = DateTimeExtensions.CurrentTimeMillis();

            if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
            {
                refreshToken(loginUser);
            }
        }
Ejemplo n.º 4
0
        public void refreshToken(LoginUser loginUser)
        {
            loginUser.loginTime = DateTimeExtensions.CurrentTimeMillis();
            int expireTime = 30; // TO DO 这个要写在appsettiong.json文件中

            loginUser.expireTime = loginUser.loginTime + expireTime * MILLIS_MINUTE;
            // 根据uuid将loginUser缓存
            string userKey = getTokenKey(loginUser.token);

            YouGeRedisHelper.Set(userKey, loginUser, expireTime * 60);
        }
Ejemplo n.º 5
0
        long GetNewResendTime(ConnectionUDP conn)
        {
            int delayAdd = conn.MyClientControl.PingDelay +
                           (int)((float)conn.MyClientControl.PingDelay * RUDPConfig.ReSendDelay);

            if (delayAdd < RUDPConfig.ReSendDelayMin)
            {
                delayAdd = RUDPConfig.ReSendDelayMin;
            }

            return(DateTimeExtensions.CurrentTimeMillis() + delayAdd);
        }
Ejemplo n.º 6
0
        public int GetCurrentTimeId()
        {
            long current = DateTimeExtensions.CurrentTimeMillis();

            if (StartSendTime == 0)
            {
                StartSendTime = current;
            }
            int timeId = (int)(current - StartSendTime) / 1000;

            return(timeId);
        }
Ejemplo n.º 7
0
 public TxEvent(EventType type, String globalTxId, String localTxId, String parentTxId, String compensationMethod,
                int timeout, String retryMethod, int retries, params Object[] payloads)
 {
     Timestamp          = DateTimeExtensions.CurrentTimeMillis();
     Type               = type;
     GlobalTxId         = globalTxId;
     LocalTxId          = localTxId;
     ParentTxId         = parentTxId;
     CompensationMethod = compensationMethod;
     Timeout            = timeout;
     RetryMethod        = retryMethod;
     Retries            = retries;
     Payloads           = payloads;
 }
Ejemplo n.º 8
0
        /**
         * 使用指定源生成验证码
         *
         * @param verifySize 验证码长度
         * @param sources 验证码字符源
         * @return
         */
        public static string generateVerifyCode(int verifySize, string sources)
        {
            if (sources == null || sources.Length == 0)
            {
                sources = Vchar;
            }
            int           codesLen   = sources.Length;
            Random        rand       = new Random((int)DateTimeExtensions.CurrentTimeMillis());
            StringBuilder verifyCode = new StringBuilder(verifySize);

            for (int i = 0; i < verifySize; i++)
            {
                verifyCode.Append(sources[rand.Next(codesLen - 1)]);
            }
            return(verifyCode.ToString());
        }
Ejemplo n.º 9
0
        void SendDataPacket(DataPacket dataPacket, bool resend, bool twice, bool block)
        {
            lock (Conn.MyClientControl.SynLock)
            {
                long startTime = DateTimeExtensions.NanoTime();
                long t1        = DateTimeExtensions.CurrentTimeMillis();

                Conn.MyClientControl.OnSendDataPacket(Conn);

                int timeId = Conn.MyClientControl.GetCurrentTimeId();
                dataPacket.Create(timeId);

                SendRecord currentRecord = Conn.MyClientControl.GetSendRecord(timeId);
                if (!resend)
                {
                    dataPacket.FirstSendTimeId = timeId;
                    dataPacket.FirstSendTime   = DateTimeExtensions.CurrentTimeMillis();
                    currentRecord.AddSentFirst(dataPacket.Data.Length);
                    currentRecord.AddSent(dataPacket.Data.Length);
                }
                else
                {
                    SendRecord record = Conn.MyClientControl.GetSendRecord(dataPacket.FirstSendTimeId);
                    record.AddResent(dataPacket.Data.Length);
                    currentRecord.AddSent(dataPacket.Data.Length);
                }

                //try
                SendSum  += 1;
                Sum      += 1;
                UnAckMax += 1;

                Send(dataPacket.MyDatagramPacket);

                if (twice)
                {
                    Send(dataPacket.MyDatagramPacket);
                }
                if (block)
                {
                    Conn.MyClientControl.SendSleep(startTime, dataPacket.Data.Length);
                }
                TrafficEvent e = new TrafficEvent("", (long)Ran.Next(), dataPacket.Data.Length, TrafficEvent.Upload);
                Route.FireEvent(e);
            }
        }
Ejemplo n.º 10
0
        public void SendPingPacket()
        {
            int  pingId   = Math.Abs(Ran.Next());
            long pingTime = DateTimeExtensions.CurrentTimeMillis();

            PingTable.Add(pingId, pingTime);
            LastSendPingTime = DateTimeExtensions.CurrentTimeMillis();

            PingPacket pingPacket = new PingPacket(0, MyRoute.LocalClientId, pingId,
                                                   MyRoute.LocalDownloadSpeed, MyRoute.LocalUploadSpeed);

            pingPacket.DstHost = DstHost;
            pingPacket.DstPort = DstPort;

            //try
            SendPacket(pingPacket.MyDatagramPacket);
        }
Ejemplo n.º 11
0
        void SendNata(byte[] data, int offset, int length)
        {
            if (!Closed && !StreamClosed)
            {
                DataPacket dataPacket = new DataPacket(Sequence, data, 0, (short)length, Conn.ConnectId, Conn.MyRoute.LocalClientId);
                dataPacket.DstHost = DstHost;
                dataPacket.DstPort = DstPort;

                lock (SynSendTable)
                {
                    SendTable.Add(dataPacket.Sequence, dataPacket);
                }

                lock (WinOb)
                {
                    if (!Conn.MyRecevier.CheckWin())
                    {
                        //try
                        Monitor.Wait(WinOb);
                    }
                }

                bool twice = false;
                if (RUDPConfig.TwiceTcp ||
                    (RUDPConfig.DoubleSendStart && dataPacket.Sequence <= 5))
                {
                    twice = true;
                }

                SendDataPacket(dataPacket, false, twice, true);

                LastSendTime = DateTimeExtensions.CurrentTimeMillis();
                SendOffset  += 1;
                S           += dataPacket.Data.Length;
                Conn.MyClientControl.MyResendManage.AddTask(Conn, Sequence);
                Sequence += 1;
            }
            else
            {
                throw new Exception("Disconnected");
            }
        }
Ejemplo n.º 12
0
        public void Run()
        {
            while (true)
            {
                // try
                ResendItem resendItem = TaskList.Take();

                if (resendItem.Conn.IsConnected)
                {
                    long sleepTime = resendItem.ResendTime - DateTimeExtensions.CurrentTimeMillis();
                    if (sleepTime > 0)
                    {
                        while (sleepTime - Int32.MaxValue > 0)
                        {
                            sleepTime -= Int32.MaxValue;
                            Thread.Sleep(Int32.MaxValue);
                        }
                        Thread.Sleep((int)sleepTime);
                    }
                    resendItem.AddCount();

                    if (resendItem.Conn.MySender.GetDataPacket(resendItem.Sequence) != null)
                    {
                        if (!resendItem.Conn.StopNow)
                        {
                            resendItem.Conn.MySender.Resend(resendItem.Sequence, resendItem.Count);
                        }
                    }

                    if (resendItem.Count < RUDPConfig.ReSendTryTimes)
                    {
                        resendItem.ResendTime = GetNewResendTime(resendItem.Conn);
                        TaskList.Add(resendItem);
                    }
                }
                if (resendItem.Conn.MyClientControl.Closed)
                {
                    break;
                }
            }
        }
Ejemplo n.º 13
0
        public static void Main(string[] args)
        {
            string host;
            string topicName;
            int    count;
            int    size;

            if (args.Length < 4)
            {
                host      = "192.168.33.12:9092";
                topicName = "test";
                count     = 10000000;
                size      = 100;
            }
            else
            {
                host      = args[0];
                topicName = args[1];
                count     = int.Parse(args[2]);
                size      = int.Parse(args[3]);
            }

            var payload = Encoding.UTF8.GetBytes(string.Join("", Enumerable.Range(0, size).Select(x => 'a')));

            var partition = RdKafkaPartitionUa;
            var errsize   = 0;
            var errstr    = IntPtr.Zero;
            var conf      = Internal.rd_kafka_conf_new();


            Internal.rd_kafka_conf_set_dr_msg_cb(conf, (IntPtr rk, ref rd_kafka_message msg, IntPtr opaque) =>
            {
                var gch = GCHandle.FromIntPtr(msg._private);
                var cb  = (Internal.OpaqueCallback)gch.Target;
                gch.Free();
                cb();
            });

//            Internal.rd_kafka_conf_set(conf, "batch.num.messages", "100", errstr, errsize);
//            Internal.rd_kafka_conf_set(conf, "queue.buffering.max.ms", "10", errstr, errsize);
//            Internal.rd_kafka_conf_set(conf, "queue.buffering.max.messages", "10000000", errstr, errsize);

            var kafka = Internal.rd_kafka_new(RdKafkaType.Producer, conf, errstr, errsize);

            Internal.rd_kafka_brokers_add(kafka, host);
            var topicConf = Internal.rd_kafka_topic_conf_new();
            var topic     = Internal.rd_kafka_topic_new(kafka, topicName, topicConf);

            var stats     = new Stats(count, 5000, Console.WriteLine);
            var queueFull = 0;

            for (int i = 0; i < count; i++)
            {
                var sendStart = DateTimeExtensions.CurrentTimeMillis();
                Internal.OpaqueCallback cb = () => stats.NextCompletion(sendStart, size, stats)();
                var gch = GCHandle.Alloc(cb);
                if (Internal.rd_kafka_produce(topic, partition, MsgFlags.None, payload, size, null, 0, GCHandle.ToIntPtr(gch)) == -1)
                {
                    Internal.rd_kafka_poll(kafka, 10);
                    gch.Free();
                    queueFull++;
                    continue;
                }
                Internal.rd_kafka_poll(kafka, 0);
            }

            while (Internal.rd_kafka_outq_len(kafka) > 0)
            {
                Internal.rd_kafka_poll(kafka, 100);
            }

            Internal.rd_kafka_topic_destroy(topic);
            Internal.rd_kafka_destroy(kafka);

            stats.PrintTotal();
            Console.WriteLine(queueFull);
        }
Ejemplo n.º 14
0
 public void Live() => LastLiveTime = DateTimeExtensions.CurrentTimeMillis();
Ejemplo n.º 15
0
        public async Task <ReturnT> InvokeService(MethodBase method, List <string> paramTypes, params object[] parameters)
        {
            var methodName = method.Name.Substring(0, 1).ToLower() + method.Name.Substring(1);
            var request    = new RpcRequest()
            {
                createMillisTime = DateTimeExtensions.CurrentTimeMillis(),
                accessToken      = _executorOption.Value.AccessToken,
                className        = "com.xxl.job.core.biz.AdminBiz",
                methodName       = methodName,
                parameterTypes   = new ArrayList(paramTypes.Select(item => new Class(item)).ToArray()),
                parameters       = new ArrayList(parameters)
            };

            var ms         = new MemoryStream();
            var serializer = new CHessianOutput(ms);

            serializer.WriteObject(request);
            var responseBody = ms.ToArray();

            int triedTimes = 0;

            while (triedTimes++ < _addresses.Count)
            {
                var item = _addresses[_currentAdminIndex];
                _currentAdminIndex = (_currentAdminIndex + 1) % _addresses.Count;
                if (!item.CheckAccessable())
                {
                    continue;
                }

                Stream responseStream;
                try
                {
                    var content = new ByteArrayContent(responseBody);
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    var responseMessage = await _client.PostAsync(item.RequestUri, content);

                    responseMessage.EnsureSuccessStatusCode();
                    responseStream = await responseMessage.Content.ReadAsStreamAsync();

                    item.Reset();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "request admin error.");
                    item.SetFail();
                    continue;
                }

                var rpcResponse = (RpcResponse) new CHessianInput(responseStream).ReadObject();
                if (rpcResponse == null)
                {
                    throw new Exception("xxl-rpc response not found.");
                }
                if (rpcResponse.IsError)
                {
                    throw new Exception(rpcResponse.error);
                }
                else
                {
                    return(rpcResponse.result as ReturnT);
                }
            }

            throw new Exception("xxl-rpc server address not accessable.");
        }