Ejemplo n.º 1
0
        public void Ready(PipeHandler worker)
        {
            Contract contract = new Contract {
                Command = MessageTypeEnum.Ready
            };

            worker.Send(contract);
        }
Ejemplo n.º 2
0
 public PipeWatcher(TableConfig config, PipeHandler handler)
     : base(config, null)
 {
     //_port = mqconfig.Port;
     //_host.OnPipeReceive += _host_OnPipeReceive;
     _handler = handler;
     _sender  = handler;
 }
Ejemplo n.º 3
0
        public virtual void Start()
        {
            _logger.Write("启动中。。");
            _manager.InitWorker();

            List <Task> list  = new List <Task>();
            int         count = 0;
            List <Task> inner = new List <Task>();

            MQFactory.Consumerconfig.ForEach(t =>
            {
                var innerTask = new Task(() =>
                {
                    while (true)
                    {
                        _logger.Write("正在准备连接服务器:" + t.ProxyIP);
                        var config  = _manager.Config.Find(p => p.Host.Equals(t.ProxyIP));
                        var worker  = _manager.GetWorker(config);
                        var hanlder = new PipeHandler(worker.Pipe);
                        try
                        {
                            _logger.Write("已连接,准备完成");
                            Ready(hanlder);
                            _logger.Write("开始接收消息队列数据");
                            count = StartConsumer(t, worker);
                            SendFinish(hanlder);
                            _logger.Write("服务器:" + t.ProxyIP + "发送了" + count.ToString() + "条消费消息");

                            var produceconfig = MQFactory.Producerconfig.Find(p => p.ProxyIP.Equals(t.ProxyIP));
                            count             = ReceiveMsg(hanlder, produceconfig);
                            _logger.Write("从服务器:" + produceconfig.ProxyIP + "接受了" + count.ToString() + "生产消息,并推送到消息队列");
                        }
                        catch (SocketException ex)//发生socket异常,重连
                        {
                            _logger.WriteException(ex);
                            worker.Close();
                            _manager.CreateWorker(config);
                            Thread.Sleep(1000 * 10);
                        }
                        catch (TimeoutException ex)//发生超时异常,重连
                        {
                            _logger.WriteException(ex);
                            worker.Close();
                            _manager.CreateWorker(config);
                            Thread.Sleep(1000 * 10);
                        }
                        catch (Exception ex)
                        {
                            _logger.WriteException(ex);
                        }

                        Thread.Sleep(1000 * 5);
                    }
                });
                inner.Add(innerTask);
                innerTask.Start();
            });
        }
Ejemplo n.º 4
0
        protected void SendFinish(PipeHandler worker)
        {
            Contract end = new Contract {
                Command = MessageTypeEnum.End
            };
            var json = JsonHelper.Serialize(end);

            worker.Send(json);
        }
Ejemplo n.º 5
0
        private void StartWatcher(ChainwayMQConfig t, ref int count)
        {
            while (true)
            {
                if (Stop)
                {
                    break;
                }
                _logger.Write("正在准备连接服务器:" + t.ProxyIP);
                var config = _manager.Config.Find(p => p.Host.Equals(t.ProxyIP));
                var worker = _manager.GetWorker(config);
                try
                {
                    var hanlder = new PipeHandler(worker.Pipe);
                    _workerDic[t.ProxyIP] = hanlder;
                    _logger.Write("已连接,准备完成");
                    Ready(hanlder);
                    _logger.Write("开始接收消息队列数据");
                    count = Consume(worker, Stop);
                    _logger.Write("处理消息队列结束,准备发送结束信息");
                    SendFinish(hanlder);
                    _logger.Write("服务器:" + t.ProxyIP + "发送了" + count.ToString() + "条消费消息");
                    _logger.Write("接收消息队列数据结束");

                    var produceconfig = MQFactory.Producerconfig.Find(p => p.ProxyIP.Equals(t.ProxyIP));
                    count = ReceiveMsg(hanlder, produceconfig, Stop);
                    _logger.Write("从服务器:" + produceconfig.ProxyIP + "接受了" + count.ToString() + "生产消息,并推送到消息队列");
                }
                catch (SocketException ex)//发生socket异常,重连
                {
                    _logger.WriteException(ex);
                    Thread.Sleep(1000 * 10);
                    worker.Close();
                    _manager.InitWorker();
                }
                catch (TimeoutException ex)//发生超时异常,重连
                {
                    _logger.WriteException(ex);
                    Thread.Sleep(1000 * 10);
                    worker.Close();
                    _manager.InitWorker();
                }
                catch (Exception ex)
                {
                    _logger.WriteException(ex);
                    _manager.InitWorker();
                }

                Thread.Sleep(1000 * 5);
            }
        }
Ejemplo n.º 6
0
        protected int ReceiveMsg(PipeHandler worker, ChainwayMQConfig config, bool stop = false)
        {
            int count = 0;

            while (true)
            {
                if (stop)
                {
                    break;
                }
                string json = worker.Receive(120);
                if (string.IsNullOrEmpty(json))
                {
                    throw new TimeoutException("接收主机信息超时");
                }
                Contract data = JsonHelper.Deserialize <Contract>(json);
                switch (data.Command)
                {
                case MessageTypeEnum.Work:
                    Contract result = new Contract();
                    try
                    {
                        ChainwayProducer producer = GetProducer(config.Group, config.Address);
                        foreach (var t in config.Topic)
                        {
                            ChainwayMessage msg = new ChainwayMessage(t);
                            msg.setKeys(data.Keys);
                            msg.setTags(data.Tags);
                            msg.Body = data.Data;
                            producer.send(msg);
                            count++;
                            _logger.Debug(string.Format("表{0}成功推送1条数据到消息队列,json:{1}", data.Keys, data.Data));
                        }
                        result.Command = MessageTypeEnum.OK;
                    }
                    catch (Exception ex)
                    {
                        result.Command = MessageTypeEnum.Error;
                        result.Message = ex.Message;
                        _logger.WriteException(ex);
                    }
                    worker.Send(result);
                    break;

                case MessageTypeEnum.End:
                    return(count);
                }
            }
            return(count);
        }
Ejemplo n.º 7
0
        protected Contract SendMessage(string group, Contract contract, PipeWorker worker)
        {
            string      json    = JsonHelper.Serialize(contract);
            var         config  = MQFactory.Consumerconfig.Find(t => t.Group.Equals(group));
            PipeHandler handler = new PipeHandler(worker.Pipe);

            handler.Send(json);
            var responseString = handler.Receive(30);

            if (string.IsNullOrEmpty(responseString))
            {
                throw new TimeoutException("接收消费回执超时");
            }
            var response = JsonHelper.Deserialize <Contract>(responseString);

            return(response);
        }
Ejemplo n.º 8
0
        public frmUNIcastStreamer()
        {
            InitializeComponent();

            // Clear sample texts
            lblSubject.Text = String.Empty;
            lblLecturer.Text = String.Empty;
            lblDate.Text = String.Empty;

            // Fix screen position bug
            this.StartPosition = FormStartPosition.CenterScreen;

            // Load settings
            IniFile ini = new IniFile(Path.Combine(Environment.CurrentDirectory, IniFile));
            string str = ini.IniReadValue(Section, KeyStream);
            if (!Address.TryParse(str, out streamAddress))
            {
                streamAddress = DefaultStreamAddress;
                ini.IniWriteValue(Section, KeyStream, streamAddress.ToString());
            }
            str = ini.IniReadValue(Section, KeyMessage);
            if (!Address.TryParse(str, out messageAddress))
            {
                messageAddress = DefaultMessageAddress;
                ini.IniWriteValue(Section, KeyMessage, messageAddress.ToString());
            }

            // Load DeckLink API
            Thread deckLinkStreamerThread = new Thread(() =>
            {
                deckLinkStreamer = new DeckLinkStreamer();

                // Set callback
                deckLinkStreamer.SetCallback(this);

                // Initialise API
                if (!deckLinkStreamer.TryInitializeAPI())
                {
                    deckLinkStreamer.SetCallback(null);
                    MessageBox.Show(strings.errorDeckLinkDriver, strings.error);
                    Environment.Exit(1);
                }

                deckLinkAPIVersion = deckLinkStreamer.DeckLinkAPIVersion;
                lblDeckLinkVersion.InvokeIfRequired(c => c.Text = deckLinkAPIVersion);
            });
            deckLinkStreamerThread.SetApartmentState(ApartmentState.MTA);
            deckLinkStreamerThread.IsBackground = true;
            deckLinkStreamerThread.Start();

            // Initialise variables, load settings
            duration = new TimeSpan(1, 30, 00);
            timeMode = 0;
            timer = new System.Windows.Forms.Timer();
            timer.Tick += timer_Tick;

            tabControl.SelectedIndex = 0;

            progressRing.ProgressPercentage = 0;

            isStreaming = false;

            streamServer = new MulticastServer(streamAddress.IP, streamAddress.Port, TTL);
            messageServer = new MulticastServer(messageAddress.IP, messageAddress.Port, TTL);
            Thread inputMonitorThread = new Thread(() =>
            {
                inputMonitor = new InputMonitor();
                inputMonitor.InputPositionReceived += inputMonitor_InputPositionReceived;
                inputMonitor.Start();
            });
            inputMonitorThread.IsBackground = true;
            inputMonitorThread.Start();

            ffmpeg = new FFmpeg();
            if (ffmpeg.isAvailable)
            {
                //ffmpeg.OnLogDataReceived += ffmpeg_LogDataReceived;
                ffmpegVersion = ffmpeg.GetVersion();
                lblFFmpegVersion.Text = ffmpegVersion;
            }

            pipeHandler = new PipeHandler();
            pipeHandler.ClientConnected += pipeHandler_ClientConnected;
            pipeHandler.ClientDisconnected += pipeHandler_ClientDisconnected;
            //else
            //{
            //    MessageBox.Show(strings.errorFFmpeg, strings.error);
            //    Environment.Exit(1);
            //}

            //performanceMonitor = new PerformanceMonitor(new string[] { "ffmpeg", "BMDStreamingServer", Process.GetCurrentProcess().ProcessName });
            //performanceMonitor.PerfValuesReceived += performanceMonitor_PerfValuesReceived;
            //performanceMonitor.StartMonitoring();

            lblVersion.Text += Application.ProductVersion;

            progressRing.Enabled = true;

            messenger = new frmMessenger();
        }
Ejemplo n.º 9
0
 void Start()
 {
     instance = this;
 }
Ejemplo n.º 10
0
        public override void SendData(Contract data, object sender)
        {
            PipeHandler handler = sender as PipeHandler;

            handler.Send(data);
        }
        public static void DequeueAndWriteMessageProc(object stateInfo)
        {
            Contract.Requires(null != stateInfo);
            var instance = stateInfo as NamedPipeTraceListener;

            Contract.Assert(null != instance);

            var sw = Stopwatch.StartNew();
            var hasExceptionOccurred = false;
            var pipeMessage          = default(PipeMessage);

            for (;;)
            {
                try
                {
                    using (var client = new NamedPipeClientStream(SERVER_NAME, instance.PipeName, PipeDirection.Out))
                    {
                        //new DefaultTraceListener().WriteLine(string.Format(MESSAGE_NAMEDPIPE_CONNECTING, instance.PipeName));

                        // NamedPipeClientStream.Connect actually spins waiting for a connection
                        // we therefore split the connection process into separate retries
                        const int count = 5;
                        for (var c = 0; c < count; c++)
                        {
                            client.Connect(NAMED_PIPE_CONNECT_AND_DEQUEUE_TIMEOUT_MS / count);
                            if (client.IsConnected)
                            {
                                break;
                            }

                            Thread.Yield();
                        }
                        client.ReadMode = PipeTransmissionMode.Message;

                        var pipeHandler = new PipeHandler(client);

                        // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                        if (hasExceptionOccurred && null != pipeMessage && pipeMessage.IsValid())
                        {
                            pipeHandler.Write(pipeMessage.ToString());

                            hasExceptionOccurred = false;
                        }

                        for (;;)
                        {
                            if (!client.IsConnected)
                            {
                                new DefaultTraceListener().WriteLine(string.Format(MESSAGE_NAMEDPIPE_NOT_CONNECTED, instance.PipeName));
                                break;
                            }

                            if (instance.useBlockingCollection)
                            {
                                pipeMessage = instance.blockingCollection.Take();
                            }
                            else
                            {
                                var result = instance.circularQueue.TryDequeue(out pipeMessage, NAMED_PIPE_CONNECT_AND_DEQUEUE_TIMEOUT_MS);

                                if (!result || ABORT_EVENT_TIMEOUT_CHECK_MS < sw.ElapsedMilliseconds)
                                {
                                    sw.Restart();
                                    if (instance.abortMessageProc)
                                    {
                                        return;
                                    }

                                    continue;
                                }
                            }

                            pipeHandler.Write(pipeMessage.ToString());
                        }
                    }
                }
                catch (TimeoutException)
                {
                    hasExceptionOccurred = true;

                    Thread.Sleep(NAMED_PIPE_CONNECT_AND_DEQUEUE_TIMEOUT_MS);
                }
                catch (IOException ex)
                {
                    hasExceptionOccurred = true;

                    new DefaultTraceListener().WriteLine(string.Format(MESSAGE_NAMEDPIPE_IOEXCEPTION, ex.Message));

                    Thread.Sleep(NAMED_PIPE_CONNECT_AND_DEQUEUE_TIMEOUT_MS);
                }
                catch (Exception ex)
                {
                    hasExceptionOccurred = true;

                    new DefaultTraceListener().WriteLine(string.Format(MESSAGE_NAMEDPIPE_EXCEPTION, ex.GetType().Name, ex.Message, ex.StackTrace));

                    Thread.Sleep(NAMED_PIPE_CONNECT_AND_DEQUEUE_TIMEOUT_MS);
                }
            }
        }
Ejemplo n.º 12
0
 public CommandService(PipeHandler callback)
 {
     this.callback = callback;
 }