Example #1
0
 /// <summary>
 /// 加入语音播放队列
 /// </summary>
 /// <param name="text"></param>
 public static void Speak(string text)
 {
     lock (MsgQueue)
     {
         MsgQueue.Add(text);
     }
 }
Example #2
0
        public void MsgQueueHandler_Basic()
        {
            MsgQueueHandler handler = null;
            MsgQueue        queue   = null;

            ClearFolder();

            try
            {
                handler = new MsgQueueHandler();
                handler.Start(router, null, null, null);

                queue = new MsgQueue(router);

                queue.EnqueueTo("foo", new QueuedMsg("bar"));
                Assert.AreEqual("bar", queue.DequeueFrom("foo", TimeSpan.FromSeconds(1)).Body);
            }
            finally
            {
                if (handler != null)
                {
                    handler.Stop();
                }

                if (queue != null)
                {
                    queue.Close();
                }
            }
        }
Example #3
0
        private void ThreadProc()
        {
            while (IsRunning)
            {
                var msg = MsgQueue.Dequeue();
                if (msg != null)
                {
                    var id = msg.SenderConnection.RemoteUniqueIdentifier;
                    if (MessageCallback != null)
                    {
                        MessageCallback(msg);
                    }

                    lock (Locker)
                    {
                        ClientIdSet[id]--;
                        if (ClientIdSet[id] <= 0)
                        {
                            ClientIdSet.Remove(id);
                        }
                    }
                }
                Thread.Sleep(0);
            }
        }
Example #4
0
        // **********************************************************************

        void RefreshTick(object sender, EventArgs e)
        {
            if (MsgQueue.Length > 0)
            {
                MsgQueue.Process();
            }

            if (SpreadsQueue.Length > 0)
            {
                SpreadsQueue.Process();
            }

            if (TicksQueue.Length > 0)
            {
                TicksQueue.Process();
            }

            if (SettingsQueue.Length > 0)
            {
                SettingsQueue.Process();
            }

            if (TradesQueue.Length > 0)
            {
                TradesQueue.Process();
            }

            if (OrdersList.QueueLength > 0)
            {
                OrdersList.UpdateHandlers();
            }
        }
Example #5
0
 public void Dispose()
 {
     if (MsgQueue != null)
     {
         MsgQueue.Dispose();
     }
 }
 public LRMWorkerThread(ILegacyLogger i_Logger, MsgQueue i_aqMsgIn, bool i_bDesktopRuntime)
 {
     m_Logger          = i_Logger;
     m_aqMsgIn         = i_aqMsgIn;
     m_aProcs          = new SBProcesses();
     m_bDesktopRuntime = i_bDesktopRuntime;
 }         // LRMWorkerThread constructor
Example #7
0
        public void SendData(byte[] data)
        {
            var response = new ZMessage {
                new ZFrame(data)
            };

            MsgQueue.Enqueue(response);
        }
Example #8
0
        public IReadOnlyList <AppMsg> DequeueMessages(params AppMsg[] addenda)
        {
            Enqueue(addenda);
            var messages = MsgQueue.ToArray();

            MsgQueue.Clear();
            return(messages);
        }
Example #9
0
        public void SendAudio(byte[] message)
        {
            var response = new ZMessage {
                new ZFrame("Master Unit2"), new ZFrame(message)
            };

            MsgQueue.Enqueue(response);
        }
Example #10
0
        //---------------------------------------------------------------------
        // Background thread

        /// <summary>
        /// The background thread.
        /// </summary>
        private void BkThread()
        {
            long startCount;

            while (true)
            {
                startCount = HiResTimer.Count;

                try
                {
                    // Sent 100 messages to a queue.

                    using (var queue = new MsgQueue(MainForm.Router))
                    {
                        for (int i = 0; i < 100; i++)
                        {
                            queue.EnqueueTo(queueEP, new QueuedMsg(i));
                            Interlocked.Increment(ref cTotal);
                        }
                    }

                    // Read the 100 messages back from the queue within a transaction
                    // and verify that we got all of them.

                    using (var queue = new MsgQueue(MainForm.Router))
                    {
                        var found = new bool[100];

                        for (int i = 0; i < 50; i++)
                        {
                            using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew))
                            {
                                found[(int)queue.DequeueFrom(queueEP).Body] = true;
                                Interlocked.Increment(ref cTotal);

                                found[(int)queue.DequeueFrom(queueEP).Body] = true;
                                Interlocked.Increment(ref cTotal);

                                scope.Complete();
                            }
                        }

                        for (int i = 0; i < found.Length; i++)
                        {
                            if (!found[i])
                            {
                                status = false;
                            }
                        }
                    }
                }
                catch
                {
                    status = false;
                }
            }
        }
Example #11
0
        /// <summary>
        /// 清空队列
        /// </summary>
        private void Clear()
        {
            T item;

            while (MsgQueue.TryDequeue(out item))
            {
                // do nothing
            }
        }
Example #12
0
        public void TestCount(int num)
        {
            var queue = new MsgQueue <int>();

            for (int i = 0; i < num; i++)
            {
                queue.Enqueue(i);
            }
            Assert.Equal(num, queue.Count);
        }
Example #13
0
        public UdpMsgListenerThread(ILegacyLogger i_Logger, MsgQueue i_aqMsgIn)
        {
            int iPort = 0;

            m_Logger             = i_Logger;
            m_aqMsgIn            = i_aqMsgIn;
            iPort                = int.Parse(ConfigurationManager.AppSettings["UdpListenPort"]);
            m_IPEndPoint         = new IPEndPoint(IPAddress.Any, iPort); // Accept any source
            m_receivingUdpClient = new UdpClient(m_IPEndPoint);
        }                                                                // UdpMsgListenerThread contstructor
        public void CreateQueue(int userId, int nodeId, string queueName, List <List <int> > readers)
        {
            using (var ctx = new MessagingContext())
            {
                var u = ctx.Users.Include(user => user.Queues).First(user => user.Id == userId && user.IssueNodeId == nodeId);

                if (u == null)
                {
                    throw new Exception("Invalid userId");
                }

                if (u.Queues == null)
                {
                    u.Queues = new List <MsgQueue>();
                }

                if (u.Queues.Find(queue => (queue.Name == queueName)) != null)
                {
                    throw new Exception("Invalid queue name: Already exists");
                }

                if (u.Queues.Count >= Config <int> .GetInstance()["USER_MAX_QUEUES"])
                {
                    throw new Exception("User has too many queues.");
                }

                /* Create a dictionary with mapping for everyone */
                var newQueue = new MsgQueue()
                {
                    Name = queueName, TopMsgIdx = 0, Readers = new List <Reader>()
                };

                foreach (var uid in readers)
                {
                    var reader = ctx.Users.Find(uid[0], uid[1]);

                    /* Invalid reader Id */
                    if (reader == null)
                    {
                        continue;
                    }

                    var r = new Reader {
                        User = reader, Position = newQueue.TopMsgIdx - 1, NodeId = nodeId, UserId = userId, Queue = newQueue
                    };

                    ctx.Readers.Add(r);
                    newQueue.Readers.Add(r);
                }

                u.Queues.Add(newQueue);

                ctx.SaveChanges();
            }
        }
        private void CleanOldMessageQueues(MessagingContext ctx, MsgQueue q)
        {
            /* Clean old messages */
            foreach (var m in q.Messages.FindAll(m => ((m.Timestamp + Config <int> .GetInstance()["QUEUE_MESSAGE_MAX_AGE"]) / 100 < DateTime.UtcNow.Ticks / 100)))
            {
                q.Messages.Remove(m);
                ctx.Messages.Remove(m);
            }

            ctx.SaveChanges();
        }
Example #16
0
        public void SendAudio(ZMessage message)
        {
            var response = new ZMessage();

            response.Add(new ZFrame(message[0].ToString() == "Master Unit" ? "Master Unit2" : "Master Unit"));
            for (int i = 1; i < message.Count; i++)
            {
                response.Add(message[i].Duplicate());
            }

            MsgQueue.Enqueue(response);
        }
Example #17
0
        public void AddMessage(NetIncomingMessage msg)
        {
            lock (Locker)
            {
                MsgQueue.Enqueue(msg);
                if (!ClientIdSet.ContainsKey(msg.SenderConnection.RemoteUniqueIdentifier))
                {
                    ClientIdSet[msg.SenderConnection.RemoteUniqueIdentifier] = 0;
                }

                ClientIdSet[msg.SenderConnection.RemoteUniqueIdentifier]++;
            }
        }
Example #18
0
        public async Task TestMsgQueueDequeue()
        {
            var queue = new MsgQueue <int>();

            _ = Task.Run(async() =>
            {
                await Task.Delay(1000);
                queue.Enqueue(50);
            });
            var val = await queue.DequeueAsync();

            Assert.Equal(50, val);
        }
    /// <summary>
    /// Add a msgqueue, if it exists, return it, otherwise, add a new one;
    /// </summary>
    public static MsgQueue AddMsgQueue(MsgQueueID msgQueueId)
    {
        if(mMsgQueueDictionary == null)
            mMsgQueueDictionary = new Dictionary<MsgQueueID, MsgQueue>();

        if (mMsgQueueDictionary.ContainsKey(msgQueueId))
            return mMsgQueueDictionary[msgQueueId];
        
        //Add msgqueue
        MsgQueue msgQueue = new MsgQueue(msgQueueId);
        mMsgQueueDictionary.Add(msgQueueId, msgQueue);

        return msgQueue;
    }
Example #20
0
        public async Task TestMsgQueueWait()
        {
            int n     = 0;
            var queue = new MsgQueue <int>();

            _ = Task.Run(async() =>
            {
                await Task.Delay(1000);
                n = 100;
                queue.Enqueue(50);
            });
            var val = await queue.DequeueAsync();

            Assert.Equal(100, n);
        }
Example #21
0
        public async Task TestStartQueueTask()
        {
            int num   = 0;
            var queue = new MsgQueue <int>();

            _ = Utils.StartQueuedTask(queue, i =>
            {
                num += i;
                return(Task.CompletedTask);
            });
            queue.Enqueue(50);
            queue.Enqueue(60);
            await Task.Delay(100);

            Assert.Equal(110, num);
        }
Example #22
0
 public void Execute()
 {
     try
     {
         mq        = new MsgQueue(this);
         mq.socket = socket;
         mq.ServerListen();
     }
     catch (Exception ex)
     {
         Console.WriteLine("[警告:来自 Program.Excute] " + ex.Message);
         if (ex.Message.Contains("time"))
         {
             Console.WriteLine("[警告:服务器用户并发数已经达到上限,资源不足,请重新启动服务器端程序,或者设置更大的并发性数上限(同时对硬件也要有更高的要求)] ");
             Environment.Exit(0);
         }
     }
     try
     {
         socket.Close();
     }
     catch (Exception ex)
     {
         Console.WriteLine("[警告:来自 Program.socket.Close()] " + ex.Message);
     }
     ////////////////////////////////////////////////////////////////////////////////////////////////////////
     if (id != null && Program.onlineClients.ContainsKey(id))
     {
         Program.onlineClients.Remove(id);
         SqlDataReader sdr = SqlserverDB.Query("select crtid from groups where id in (select groupid from relations where fndid='" + id + "')");
         while (sdr.Read())
         {
             String oid = sdr.GetString(0);
             if (Program.onlineClients.ContainsKey(oid))
             {
                 SendMessage(oid, "frdstt", new String[] { id, "False" });
             }
         }
         SqlserverDB.Free(sdr);
         Console.WriteLine(DateTime.Now.ToString() + ":断开与用户'" + id + "'连接!");
     }
     else
     {
         Console.WriteLine("断开一个无效连接!");
     }
 }
Example #23
0
        protected void TaskProc()
        {
            while (!CancelSource.IsCancellationRequested)
            {
                MsgSem.WaitOne();

                if (CancelSource.IsCancellationRequested)
                {
                    break;
                }

                T value = default(T);
                if (MsgQueue.TryDequeue(out value))
                {
                    InvokerAction?.Invoke(value);
                }
            }
        }
Example #24
0
        }         // StartListenerThread

        protected static Thread StartWorkerThread(ILegacyLogger i_Logger, MsgQueue i_aqMsgIn, bool i_bDesktopRuntime)
        {
            Thread          tRet   = null;
            LRMWorkerThread worker = null;

            try
            {
                worker = new LRMWorkerThread(i_Logger, i_aqMsgIn, i_bDesktopRuntime);
                tRet   = new Thread(new ThreadStart(worker.ThreadProc));
                tRet.Start();
            }
            catch (Exception exc)
            {
                i_Logger.Log(Level.Exception, "SBLocalRM.StartWorkerThread caught exception: " + exc.ToString());
            }

            return(tRet);
        }         // StartWorkerThread
Example #25
0
        }         // Start Loggers

        protected static Thread StartListenerThread(ILegacyLogger i_Logger, MsgQueue i_aqMsgIn)
        {
            Thread tRet = null;
            UdpMsgListenerThread listener = null;

            try
            {
                listener = new UdpMsgListenerThread(i_Logger, i_aqMsgIn);
                tRet     = new Thread(new ThreadStart(listener.ThreadProc));
                tRet.Start();
            }
            catch (Exception exc)
            {
                i_Logger.Log(Level.Exception, "SBLocalRM.StartListenerThread caught exception: " + exc.ToString());
            }

            return(tRet);
        }         // StartListenerThread
Example #26
0
        public async Task TestStartQueueTask(params int[] nums)
        {
            var msgs = new MsgQueue <int>();
            int num  = 0;

            _ = Utils.StartQueuedTask(msgs, (i) =>
            {
                num += i;
                return(Task.CompletedTask);
            });
            foreach (var item in nums)
            {
                msgs.Enqueue(item);
            }
            await Task.Delay(100);

            Assert.Equal(nums.Sum(), num);
        }
Example #27
0
    /// <summary>
    /// Add a msgqueue, if it exists, return it, otherwise, add a new one;
    /// </summary>
    public static MsgQueue AddMsgQueue(MsgQueueID msgQueueId)
    {
        if (mMsgQueueDictionary == null)
        {
            mMsgQueueDictionary = new Dictionary <MsgQueueID, MsgQueue>();
        }

        if (mMsgQueueDictionary.ContainsKey(msgQueueId))
        {
            return(mMsgQueueDictionary[msgQueueId]);
        }

        //Add msgqueue
        MsgQueue msgQueue = new MsgQueue(msgQueueId);

        mMsgQueueDictionary.Add(msgQueueId, msgQueue);

        return(msgQueue);
    }
Example #28
0
        public async Task TestIAsyncEnumerableCancel()
        {
            var queue    = new MsgQueue <int>();
            var tokenSrc = new CancellationTokenSource();

            _ = Task.Run(() =>
            {
                tokenSrc.CancelAfter(100);
            });
            try
            {
                await foreach (var item in queue.WithCancellation(tokenSrc.Token))
                {
                }
            }
            catch (System.Exception e)
            {
                Assert.IsType <OperationCanceledException>(e);
            }
        }
Example #29
0
        private static void SynthesizerSpeakCompleted(object sender, SpeakCompletedEventArgs e)
        {
            //Console.WriteLine($"speak thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");

            OnTextSpeaking(SpeakingText);

            //语音播放用线程池中的线程来操作
            ThreadPool.QueueUserWorkItem(state =>
            {
                Player.Stream.Position = 0;
                Player.PlaySync();//同步播放

                //删除第一条语音,并设置读状态为假
                lock (MsgQueue)
                {
                    MsgQueue.RemoveAt(0);
                }

                Speaking = false;
            });
        }
Example #30
0
        public async Task TestIAsyncEnumerableApi()
        {
            int num   = 0;
            var queue = new MsgQueue <int>();

            _ = Task.Run(() =>
            {
                queue.Enqueue(50);
                queue.Enqueue(60);
                queue.Enqueue(70);
            });
            await Task.WhenAny(Task.Run(async() =>
            {
                await foreach (var item in queue)
                {
                    Assert.Equal(10 * num + 50, item);
                    num++;
                }
            }), Task.Delay(100));

            Assert.Equal(3, num);
        }
Example #31
0
        private void SendMailMessage(MsgQueue msg)
        {
            var config = SettingManager.Get<EmailConfig>();

            IEmailSender sender = new EmailSender(config.SmtpServer, config.SmtpPort, config.Name, config.SmtpUserName, config.SmtpPassword, config.IsSSL);

            sender.SendMail(msg.Dest, msg.Title, msg.Content, msg.ID, (o, e) => {
                                                                          var m = DbProvider().GetByID<MsgQueue>(e.UserState);
                                                                          if (e.Error != null) {
                                                                              m.IsSuccess = false;
                                                                              m.Result = e.Error.Message;
                                                                          } else {
                                                                              m.IsSuccess = true;
                                                                          }
                                                                          DbProvider().SaveChanges();
                                                                      });
        }
 /// <summary>
 /// constructor
 /// </summary>
 static MsgQueueDictionary()
 {
     mGlobalMsgQueue = AddMsgQueue(MsgQueueID.Global_MsgQueue);        //Global MsgQueue
 }
Example #33
0
        public void MessageQueue_EndToEnd_Disk()
        {
            // This test peforms a simple end-to-end test of the Message
            // Queue Service by starting the service and processing
            // some messages.

            Process    svcProcess = null;
            LeafRouter router     = null;
            MsgQueue   queue      = null;
            Assembly   assembly;

            Helper.InitializeApp(Assembly.GetExecutingAssembly());
            assembly = typeof(LillTek.Datacenter.MessageQueue.Program).Assembly;

            try
            {
                // Start a local router and open a client.

                Config.SetConfig(@"

//-----------------------------------------------------------------------------
// LeafRouter Settings

&section MsgRouter

    AppName                = LillTek.Test Router
    AppDescription         = Unit Test
    RouterEP			   = physical://DETACHED/$(LillTek.DC.DefHubName)/$(Guid)
    CloudEP                = $(LillTek.DC.CloudEP)
    CloudAdapter           = ANY
    UdpEP				   = ANY:0
    TcpEP				   = ANY:0
    TcpBacklog			   = 100
    TcpDelay			   = off
    BkInterval			   = 1s
    MaxIdle				   = 5m
    EnableP2P              = yes
    AdvertiseTime		   = 1m
    DefMsgTTL			   = 5
    SharedKey		       = PLAINTEXT
    SessionCacheTime       = 2m
    SessionRetries         = 3
    SessionTimeout         = 10s
    MaxLogicalAdvertiseEPs = 256
    DeadRouterTTL          = 2s

&endsection

".Replace('&', '#'));

                router = new LeafRouter();
                router.Start();

                // Start the application store service

                svcProcess = Helper.StartProcess(assembly, "-mode:form -start");
                Thread.Sleep(10000);    // Give the process a chance to spin up

                // Send and receive some messages

                queue = new MsgQueue(router);
                queue.EnqueueTo("logical://LillTek/DataCenter/MsgQueue/10", new QueuedMsg(10));

                //for (int i=0;i<10;i++)
                //    queue.EnqueueTo("logical://LillTek/DataCenter/MsgQueue/" + i.ToString(),new QueuedMsg(i));

                //for (int i=0;i<10;i++)
                //    Assert.AreEqual(i,queue.DequeueFrom("logical://LillTek/DataCenter/MsgQueue/" + i.ToString(),TimeSpan.FromSeconds(1)).Body);
            }
            finally
            {
                if (svcProcess != null)
                {
                    svcProcess.Kill();
                    svcProcess.Close();
                }

                if (queue != null)
                {
                    queue.Close();
                }

                if (router != null)
                {
                    router.Stop();
                }

                Config.SetConfig(null);
            }
        }
Example #34
0
        private void SendSmsMessage(MsgQueue msg)
        {
            string type = SettingManager.Get<MessageConfig>().SmsType;

            SmsServer smsSever = DbProvider().D<SmsServer>().FirstOrDefault(x => x.ClassName == type);

            if (smsSever == null) {
                var m = DbProvider().GetByID<MsgQueue>(msg.ID);
                m.IsSuccess = false;
                m.Result = "未设置默认短信通道";
                DbProvider().SaveChanges();
                return;
            }

            SMSSender sender = SMSSender.CreateInstance(new SMSAttribute {
                                                                             Config = smsSever.Config.Values.ToArray(), Name = smsSever.ServerName, SmsAccount = smsSever.UserName, SmsPassword = smsSever.Password, TypeName = smsSever.ClassName
                                                                         });

            if (sender == null) {
                var m = DbProvider().GetByID<MsgQueue>(msg.ID);
                m.IsSuccess = false;
                m.Result = "短信通道不存在";
                DbProvider().SaveChanges();
                return;
            }

            try {
                sender.Send(msg.Dest, msg.Content);
                var m = DbProvider().GetByID<MsgQueue>(msg.ID);
                m.IsSuccess = true;
                DbProvider().SaveChanges();
            }
            catch (Exception ex) {
                var m = DbProvider().GetByID<MsgQueue>(msg.ID);
                m.IsSuccess = false;
                m.Result = ex.Message;
                DbProvider().SaveChanges();
            }
        }