public void MulticastLoopback()
        {
            UdpMessagingSystemFactory aMessaging = new UdpMessagingSystemFactory(new EasyProtocolFormatter())
            {
                UnicastCommunication    = false,
                MulticastGroupToReceive = "234.1.2.3",
                MulticastLoopback       = true
            };

            ManualResetEvent     aMessageReceived = new ManualResetEvent(false);
            string               aReceivedMessage = null;
            IDuplexOutputChannel anOutputChannel  = aMessaging.CreateDuplexOutputChannel("udp://234.1.2.3:8090/", "udp://0.0.0.0:8090/");

            anOutputChannel.ResponseMessageReceived += (x, y) =>
            {
                aReceivedMessage = (string)y.Message;
                aMessageReceived.Set();
            };

            try
            {
                anOutputChannel.OpenConnection();
                anOutputChannel.SendMessage("Hello");
                aMessageReceived.WaitIfNotDebugging(1000);
            }
            finally
            {
                anOutputChannel.CloseConnection();
            }

            Assert.AreEqual("Hello", aReceivedMessage);
        }
예제 #2
0
        private bool InitializeWorkerConnection()
        {
            // Create TCP messaging
            IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();

            Worker4504OutputChannel = aMessaging.CreateDuplexOutputChannel("tcp://127.0.0.1:4504/");

            // Subscribe to response messages.
            Worker4504OutputChannel.ConnectionClosed        += Worker4504OutputChannel_ConnectionClosed;
            Worker4504OutputChannel.ConnectionOpened        += Worker4504OutputChannel_ConnectionOpened;
            Worker4504OutputChannel.ResponseMessageReceived += Worker4504OutputChannel_ResponseMessageReceived;

            // Open connection and be able to send messages and receive response messages.
            Worker4504OutputChannel.OpenConnection();
            Log("Channel id : " + Worker4504OutputChannel.ChannelId);

            // Send a message.
            byte[] data = new byte[1048576];             // initialize 1MB data
            //byte[] data = new byte[10]; // initialize 1MB data
            Random random = new Random();

            random.NextBytes(data);
            Worker4504OutputChannel.SendMessage(data);
            Log("Sent data length : " + data.Length);

            // Close connection.
            //Worker4504OutputChannel.CloseConnection();

            return(true);
        }
예제 #3
0
        public void ClientReceiveTimeout()
        {
            IMessagingSystemFactory aMessaging = new WebSocketMessagingSystemFactory()
            {
                ReceiveTimeout = TimeSpan.FromMilliseconds(1000)
            };
            IDuplexOutputChannel anOutputChannel = aMessaging.CreateDuplexOutputChannel("ws://127.0.0.1:8046/");
            IDuplexInputChannel  anInputChannel  = aMessaging.CreateDuplexInputChannel("ws://127.0.0.1:8046/");

            try
            {
                ManualResetEvent aConnectionClosed = new ManualResetEvent(false);
                anOutputChannel.ConnectionClosed += (x, y) =>
                {
                    EneterTrace.Info("Connection closed.");
                    aConnectionClosed.Set();
                };

                anInputChannel.StartListening();
                anOutputChannel.OpenConnection();

                EneterTrace.Info("Connection opened.");

                // According to set receive timeout the client should get disconnected within 1 second.
                //aConnectionClosed.WaitOne();
                Assert.IsTrue(aConnectionClosed.WaitOne(3000));
            }
            finally
            {
                anOutputChannel.CloseConnection();
                anInputChannel.StopListening();
            }
        }
예제 #4
0
            // Client opens connection to a particular output.
            public void OpenOutputConnection(IMessagingSystemFactory messaging, string channelId)
            {
                using (EneterTrace.Entering())
                {
                    IDuplexOutputChannel anOutputChannel = null;
                    try
                    {
                        using (ThreadLock.Lock(myOutputConnectionLock))
                        {
                            anOutputChannel = messaging.CreateDuplexOutputChannel(channelId);
                            anOutputChannel.ConnectionClosed        += OnConnectionClosed;
                            anOutputChannel.ResponseMessageReceived += OnResponseMessageReceived;

                            anOutputChannel.OpenConnection();

                            // Connection is successfuly open so it can be stored.
                            myOpenOutputConnections.Add(anOutputChannel);
                        }
                    }
                    catch (Exception err)
                    {
                        EneterTrace.Warning("Failed to open connection to '" + channelId + "'.", err);

                        if (anOutputChannel != null)
                        {
                            anOutputChannel.ConnectionClosed        -= OnConnectionClosed;
                            anOutputChannel.ResponseMessageReceived -= OnResponseMessageReceived;
                        }

                        throw;
                    }
                }
            }
        public void BroadcastFromClientToAllServices()
        {
            UdpMessagingSystemFactory anOutputChannelMessaging = new UdpMessagingSystemFactory(new EasyProtocolFormatter())
            {
                UnicastCommunication   = false,
                AllowSendingBroadcasts = true
            };

            UdpMessagingSystemFactory anInputChannelMessaging = new UdpMessagingSystemFactory(new EasyProtocolFormatter())
            {
                UnicastCommunication = false,
                ReuseAddress         = true
            };

            ManualResetEvent    aMessage1Received = new ManualResetEvent(false);
            string              aReceivedMessage1 = null;
            IDuplexInputChannel anInputChannel1   = anInputChannelMessaging.CreateDuplexInputChannel("udp://127.0.0.1:8095/");

            anInputChannel1.MessageReceived += (x, y) =>
            {
                aReceivedMessage1 = (string)y.Message;
                aMessage1Received.Set();
            };

            ManualResetEvent    aMessage2Received = new ManualResetEvent(false);
            string              aReceivedMessage2 = null;
            IDuplexInputChannel anInputChannel2   = anInputChannelMessaging.CreateDuplexInputChannel("udp://127.0.0.1:8095/");

            anInputChannel2.MessageReceived += (x, y) =>
            {
                aReceivedMessage2 = (string)y.Message;
                aMessage2Received.Set();
            };

            IDuplexOutputChannel anOutputChannel = anOutputChannelMessaging.CreateDuplexOutputChannel("udp://255.255.255.255:8095/", "udp://127.0.0.1");

            try
            {
                anInputChannel1.StartListening();
                anInputChannel2.StartListening();

                anOutputChannel.OpenConnection();
                anOutputChannel.SendMessage("Hello");

                aMessage1Received.WaitIfNotDebugging(1000);
                aMessage2Received.WaitIfNotDebugging(1000);
            }
            finally
            {
                anOutputChannel.CloseConnection();

                anInputChannel1.StopListening();
                anInputChannel2.StopListening();
            }

            Assert.AreEqual("Hello", aReceivedMessage1);
            Assert.AreEqual("Hello", aReceivedMessage2);
        }
        public void MulticastFromServiceToClients()
        {
            UdpMessagingSystemFactory aMessaging = new UdpMessagingSystemFactory(new EasyProtocolFormatter())
            {
                UnicastCommunication    = false,
                ReuseAddress            = true,
                MulticastGroupToReceive = "234.1.2.3",
                MulticastLoopback       = true
            };

            ManualResetEvent     aMessage1Received = new ManualResetEvent(false);
            string               aReceivedMessage1 = null;
            IDuplexOutputChannel anOutputChannel1  = aMessaging.CreateDuplexOutputChannel("udp://127.0.0.1:8090/", "udp://127.0.0.1:8092/");

            anOutputChannel1.ResponseMessageReceived += (x, y) =>
            {
                aReceivedMessage1 = (string)y.Message;
                aMessage1Received.Set();
            };

            ManualResetEvent     aMessage2Received = new ManualResetEvent(false);
            string               aReceivedMessage2 = null;
            IDuplexOutputChannel anOutputChannel2  = aMessaging.CreateDuplexOutputChannel("udp://127.0.0.1:8090/", "udp://127.0.0.1:8092/");

            anOutputChannel2.ResponseMessageReceived += (x, y) =>
            {
                aReceivedMessage2 = (string)y.Message;
                aMessage2Received.Set();
            };

            IDuplexInputChannel anInputChannel = aMessaging.CreateDuplexInputChannel("udp://127.0.0.1:8090/");

            try
            {
                anInputChannel.StartListening();

                anOutputChannel1.OpenConnection();
                anOutputChannel2.OpenConnection();

                anInputChannel.SendResponseMessage("udp://234.1.2.3:8092/", "Hello");

                aMessage1Received.WaitIfNotDebugging(1000);
                aMessage2Received.WaitIfNotDebugging(1000);
            }
            finally
            {
                anInputChannel.StopListening();

                anOutputChannel1.CloseConnection();
                anOutputChannel2.CloseConnection();
            }

            Assert.AreEqual("Hello", aReceivedMessage1);
            Assert.AreEqual("Hello", aReceivedMessage2);
        }
예제 #7
0
        public virtual void A15_ResponseReceiverReconnects_AfterStopListening()
        {
            IDuplexOutputChannel aDuplexOutputChannel = MessagingSystem.CreateDuplexOutputChannel(ChannelId);
            IDuplexInputChannel  aDuplexInputChannel  = MessagingSystem.CreateDuplexInputChannel(ChannelId);

            AutoResetEvent aConnectionsCompletedEvent = new AutoResetEvent(false);
            List <string>  anOpenConnections          = new List <string>();

            aDuplexInputChannel.ResponseReceiverConnected += (x, y) =>
            {
                lock (anOpenConnections)
                {
                    anOpenConnections.Add(y.ResponseReceiverId);
                    aConnectionsCompletedEvent.Set();
                }
            };

            try
            {
                aDuplexInputChannel.StartListening();
                aDuplexOutputChannel.OpenConnection();

                // Wait until the client is connected.
                aConnectionsCompletedEvent.WaitOne();

                // Stop listenig.
                aDuplexInputChannel.StopListening();

                // Give some time to stop.
                Thread.Sleep(700);

                // Start listening again.
                aDuplexInputChannel.StartListening();

                // The duplex output channel will try to connect again, therefore wait until connected.
                aConnectionsCompletedEvent.WaitOne();

                Assert.IsTrue(aDuplexOutputChannel.IsConnected);
            }
            finally
            {
                aDuplexOutputChannel.CloseConnection();
                aDuplexInputChannel.StopListening();
            }


            Assert.AreEqual(2, anOpenConnections.Count);

            // Both connections should be same.
            Assert.AreEqual(aDuplexOutputChannel.ResponseReceiverId, anOpenConnections[0]);
            Assert.AreEqual(aDuplexOutputChannel.ResponseReceiverId, anOpenConnections[1]);
        }
예제 #8
0
        public virtual void Duplex_07_OpenConnection_if_InputChannelNotStarted()
        {
            IDuplexOutputChannel anOutputChannel = MessagingSystemFactory.CreateDuplexOutputChannel(ChannelId);

            try
            {
                anOutputChannel.OpenConnection();
            }
            catch
            {
            }

            Assert.IsFalse(anOutputChannel.IsConnected);
        }
예제 #9
0
        public void A14_ResponseReceiverReconnects_AfterDisconnect()
        {
            // Duplex output channel without queue - it will not try to reconnect.
            IDuplexOutputChannel aDuplexOutputChannel = MessagingSystem.CreateDuplexOutputChannel(ChannelId);
            IDuplexInputChannel  aDuplexInputChannel  = MessagingSystem.CreateDuplexInputChannel(ChannelId);

            AutoResetEvent aConnectionsCompletedEvent = new AutoResetEvent(false);
            List <string>  anOpenConnections          = new List <string>();

            aDuplexInputChannel.ResponseReceiverConnected += (x, y) =>
            {
                lock (anOpenConnections)
                {
                    anOpenConnections.Add(y.ResponseReceiverId);

                    aConnectionsCompletedEvent.Set();
                }
            };

            try
            {
                aDuplexInputChannel.StartListening();
                aDuplexOutputChannel.OpenConnection();

                // Wait until the connection is open.
                aConnectionsCompletedEvent.WaitOne();

                // Disconnect the response receiver.
                aDuplexInputChannel.DisconnectResponseReceiver(aDuplexOutputChannel.ResponseReceiverId);

                // The duplex output channel will try to connect again, therefore wait until connected.
                aConnectionsCompletedEvent.WaitOne();
            }
            finally
            {
                aDuplexOutputChannel.CloseConnection();
                aDuplexInputChannel.StopListening();
            }


            Assert.AreEqual(2, anOpenConnections.Count);

            // Both connections should be same.
            Assert.AreEqual(aDuplexOutputChannel.ResponseReceiverId, anOpenConnections[0]);
            Assert.AreEqual(aDuplexOutputChannel.ResponseReceiverId, anOpenConnections[1]);
        }
        public void MaxAmountOfConnections()
        {
            IMessagingSystemFactory aMessaging = new UdpMessagingSystemFactory()
            {
                MaxAmountOfConnections = 2
            };
            IDuplexOutputChannel anOutputChannel1 = aMessaging.CreateDuplexOutputChannel("udp://127.0.0.1:8049/");
            IDuplexOutputChannel anOutputChannel2 = aMessaging.CreateDuplexOutputChannel("udp://127.0.0.1:8049/");
            IDuplexOutputChannel anOutputChannel3 = aMessaging.CreateDuplexOutputChannel("udp://127.0.0.1:8049/");
            IDuplexInputChannel  anInputChannel   = aMessaging.CreateDuplexInputChannel("udp://127.0.0.1:8049/");

            try
            {
                ManualResetEvent aConnectionClosed = new ManualResetEvent(false);
                anOutputChannel3.ConnectionClosed += (x, y) =>
                {
                    EneterTrace.Info("Connection closed.");
                    aConnectionClosed.Set();
                };


                anInputChannel.StartListening();
                anOutputChannel1.OpenConnection();
                anOutputChannel2.OpenConnection();
                anOutputChannel3.OpenConnection();

                if (!aConnectionClosed.WaitOne(1000))
                {
                    Assert.Fail("Third connection was not closed.");
                }

                Assert.IsTrue(anOutputChannel1.IsConnected);
                Assert.IsTrue(anOutputChannel2.IsConnected);
                Assert.IsFalse(anOutputChannel3.IsConnected);
            }
            finally
            {
                anOutputChannel1.CloseConnection();
                anOutputChannel2.CloseConnection();
                anOutputChannel3.CloseConnection();
                anInputChannel.StopListening();
            }
        }
        public void B01_Pinging_StopListening()
        {
            IDuplexInputChannel aDuplexInputChannel = MessagingSystemFactory.CreateDuplexInputChannel(ChannelId);

            IDuplexOutputChannel aDuplexOutputChannel = MessagingSystemFactory.CreateDuplexOutputChannel(ChannelId);

            AutoResetEvent aDisconnectedEvent = new AutoResetEvent(false);

            bool aDisconnectedFlag = false;

            aDuplexOutputChannel.ConnectionClosed += (x, y) =>
            {
                aDisconnectedFlag = true;
                aDisconnectedEvent.Set();
            };

            try
            {
                // Start listening.
                aDuplexInputChannel.StartListening();

                // Start pinging and wait 5 seconds.
                aDuplexOutputChannel.OpenConnection();
                Thread.Sleep(5000);

                Assert.IsFalse(aDisconnectedFlag);

                // Stop listener, therefore the ping response will not come and the channel should indicate the disconnection.
                aDuplexInputChannel.StopListening();

                aDisconnectedEvent.WaitOne();

                Assert.IsTrue(aDisconnectedFlag);
                Assert.IsFalse(aDuplexOutputChannel.IsConnected);
            }
            finally
            {
                aDuplexOutputChannel.CloseConnection();
                aDuplexInputChannel.StopListening();
            }
        }
예제 #12
0
        public void ConnectionTimeout()
        {
            IMessagingSystemFactory aMessaging = new WebSocketMessagingSystemFactory()
            {
                ConnectTimeout = TimeSpan.FromMilliseconds(1000)
            };

            // Nobody is listening on this address.
            IDuplexOutputChannel anOutputChannel = aMessaging.CreateDuplexOutputChannel("ws://109.74.151.135:8045/");

            ManualResetEvent aConnectionCompleted = new ManualResetEvent(false);

            try
            {
                // Start opening in another thread to be able to measure
                // if the timeout occured with the specified time.
                Exception anException = null;
                ThreadPool.QueueUserWorkItem(x =>
                {
                    try
                    {
                        anOutputChannel.OpenConnection();
                    }
                    catch (Exception err)
                    {
                        anException = err;
                    }
                    aConnectionCompleted.Set();
                });

                if (aConnectionCompleted.WaitOne(1500))
                {
                }

                Assert.AreEqual(typeof(TimeoutException), anException);
            }
            finally
            {
                anOutputChannel.CloseConnection();
            }
        }
        private IDuplexOutputChannel GetAssociatedDuplexOutputChannel(string duplexInputChannelId, string responseReceiverId, string duplexOutputChannelId)
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myDuplexInputChannelContextManipulatorLock))
                {
                    TDuplexInputChannelContext aDuplexInputChannelContext = myDuplexInputChannelContexts.FirstOrDefault(x => x.AttachedDuplexInputChannel.ChannelId == duplexInputChannelId);
                    if (aDuplexInputChannelContext == null)
                    {
                        string anError = TracedObject + "failed to return the duplex output channel associated with the duplex input channel '" + duplexInputChannelId + "' because the duplex input channel was not attached.";
                        EneterTrace.Error(anError);
                        throw new InvalidOperationException(anError);
                    }

                    TConnection aConnection = aDuplexInputChannelContext.OpenConnections.FirstOrDefault(x => x.ResponseReceiverId == responseReceiverId && x.ConnectedDuplexOutputChannel.ChannelId == duplexOutputChannelId);
                    if (aConnection == null)
                    {
                        IDuplexOutputChannel anAssociatedDuplexOutputChannel = MessagingSystemFactory.CreateDuplexOutputChannel(duplexOutputChannelId);

                        try
                        {
                            anAssociatedDuplexOutputChannel.ResponseMessageReceived += OnResponseMessageReceived;
                            anAssociatedDuplexOutputChannel.OpenConnection();
                        }
                        catch (Exception err)
                        {
                            anAssociatedDuplexOutputChannel.ResponseMessageReceived -= OnResponseMessageReceived;

                            EneterTrace.Error(TracedObject + "failed to open connection for the duplex output channel '" + duplexOutputChannelId + "'.", err);
                            throw;
                        }


                        aConnection = new TConnection(responseReceiverId, anAssociatedDuplexOutputChannel);
                        aDuplexInputChannelContext.OpenConnections.Add(aConnection);
                    }

                    return(aConnection.ConnectedDuplexOutputChannel);
                }
            }
        }
        public void B04_Pinging_CloseConnection()
        {
            IDuplexInputChannel aDuplexInputChannel = MessagingSystemFactory.CreateDuplexInputChannel(ChannelId);

            IDuplexOutputChannel aDuplexOutputChannel = MessagingSystemFactory.CreateDuplexOutputChannel(ChannelId);

            AutoResetEvent aConnectionClosedEvent    = new AutoResetEvent(false);
            string         aClosedResponseReceiverId = "";

            aDuplexInputChannel.ResponseReceiverDisconnected += (x, y) =>
            {
                aClosedResponseReceiverId = y.ResponseReceiverId;
                aConnectionClosedEvent.Set();
            };

            try
            {
                // Start listening.
                aDuplexInputChannel.StartListening();

                // Allow some time for pinging.
                aDuplexOutputChannel.OpenConnection();
                Thread.Sleep(2000);

                Assert.AreEqual("", aClosedResponseReceiverId);

                // Close connection. Therefore the duplex input channel will not get any pings anymore.
                aDuplexOutputChannel.CloseConnection();

                aConnectionClosedEvent.WaitOne();

                Assert.AreEqual(aDuplexOutputChannel.ResponseReceiverId, aClosedResponseReceiverId);
                Assert.IsFalse(aDuplexOutputChannel.IsConnected);
            }
            finally
            {
                aDuplexOutputChannel.CloseConnection();
                aDuplexInputChannel.StopListening();
            }
        }
        public void B02_Pinging_DisconnectResponseReceiver()
        {
            IDuplexInputChannel  aDuplexInputChannel  = MessagingSystemFactory.CreateDuplexInputChannel(ChannelId);
            IDuplexOutputChannel aDuplexOutputChannel = MessagingSystemFactory.CreateDuplexOutputChannel(ChannelId);

            AutoResetEvent aDisconnectedEvent = new AutoResetEvent(false);

            bool aDisconnectedFlag = false;

            aDuplexOutputChannel.ConnectionClosed += (x, y) =>
            {
                aDisconnectedFlag = true;
                aDisconnectedEvent.Set();
            };

            try
            {
                // Start listening.
                aDuplexInputChannel.StartListening();

                // Allow some time for pinging.
                aDuplexOutputChannel.OpenConnection();
                Thread.Sleep(2000);

                Assert.IsFalse(aDisconnectedFlag);

                // Disconnect the duplex output channel.
                aDuplexInputChannel.DisconnectResponseReceiver(aDuplexOutputChannel.ResponseReceiverId);

                aDisconnectedEvent.WaitOne();

                Assert.IsTrue(aDisconnectedFlag);
                Assert.IsFalse(aDuplexOutputChannel.IsConnected);
            }
            finally
            {
                aDuplexOutputChannel.CloseConnection();
                aDuplexInputChannel.StopListening();
            }
        }
예제 #16
0
        private void StartCapturing()
        {
            // Use unique name for the pipe.
            string aVideoPipeName = Guid.NewGuid().ToString();

            // Open pipe that will be read by VLC.
            myVideoPipe = new NamedPipeServerStream(@"\" + aVideoPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, 32764);
            ManualResetEvent aVlcConnectedPipe = new ManualResetEvent(false);

            ThreadPool.QueueUserWorkItem(x =>
            {
                myVideoPipe.WaitForConnection();

                // Indicate VLC has connected the pipe.
                aVlcConnectedPipe.Set();
            });

            // VLC connects the pipe and starts playing.
            using (VlcMedia aMedia = new VlcMedia(myVlcInstance, @"stream://\\\.\pipe\" + aVideoPipeName))
            {
                // Setup VLC so that it can process raw h264 data (i.e. not in mp4 container)
                aMedia.AddOption(":demux=H264");

                myPlayer          = new VlcMediaPlayer(aMedia);
                myPlayer.Drawable = VideoWindow.Child.Handle;

                // Note: This will connect the pipe and read the video.
                myPlayer.Play();
            }

            // Wait until VLC connects the pipe so that it is ready to receive the stream.
            if (!aVlcConnectedPipe.WaitOne(5000))
            {
                throw new TimeoutException("VLC did not open connection with the pipe.");
            }

            // Open connection with service running on Raspberry.
            myVideoChannel.OpenConnection();
        }
        public void B03_Pinging_NoResponseForPing()
        {
            // Create duplex input channel which will not send ping messages.
            IDuplexInputChannel aDuplexInputChannel = UnderlyingMessaging.CreateDuplexInputChannel(ChannelId);

            IDuplexOutputChannel aDuplexOutputChannel = MessagingSystemFactory.CreateDuplexOutputChannel(ChannelId);

            AutoResetEvent aDisconnectedEvent = new AutoResetEvent(false);

            bool aDisconnectedFlag = false;

            aDuplexOutputChannel.ConnectionClosed += (x, y) =>
            {
                aDisconnectedFlag = true;
                aDisconnectedEvent.Set();
            };

            try
            {
                // Start listening.
                aDuplexInputChannel.StartListening();

                // Allow some time for pinging.
                aDuplexOutputChannel.OpenConnection();
                Assert.IsTrue(aDuplexOutputChannel.IsConnected);

                Thread.Sleep(2000);

                aDisconnectedEvent.WaitOne();

                Assert.IsTrue(aDisconnectedFlag);
                Assert.IsFalse(aDuplexOutputChannel.IsConnected);
            }
            finally
            {
                aDuplexOutputChannel.CloseConnection();
                aDuplexInputChannel.StopListening();
            }
        }
        public virtual void AuthenticationTimeout()
        {
            IDuplexInputChannel  anInputChannel  = MessagingSystemFactory.CreateDuplexInputChannel(ChannelId);
            IDuplexOutputChannel anOutputChannel = MessagingSystemFactory.CreateDuplexOutputChannel(ChannelId);

            try
            {
                myAuthenticationSleep = TimeSpan.FromMilliseconds(3000);

                anInputChannel.StartListening();

                // Client opens the connection.
                Assert.Throws <TimeoutException>(() => anOutputChannel.OpenConnection());
            }
            finally
            {
                myAuthenticationSleep = TimeSpan.FromMilliseconds(0);

                anOutputChannel.CloseConnection();
                anInputChannel.StopListening();
            }
        }
        public virtual void ConnectionNotGranted()
        {
            IDuplexInputChannel  anInputChannel  = MessagingSystemFactory.CreateDuplexInputChannel(ChannelId);
            IDuplexOutputChannel anOutputChannel = MessagingSystemFactory.CreateDuplexOutputChannel(ChannelId);

            try
            {
                myConnectionNotGranted = true;

                anInputChannel.StartListening();

                // Client opens the connection.
                Assert.Throws <InvalidOperationException>(() => anOutputChannel.OpenConnection());
            }
            finally
            {
                myConnectionNotGranted = false;

                anOutputChannel.CloseConnection();
                anInputChannel.StopListening();
            }
        }
예제 #20
0
        private bool Worker4504_Initialize()
        {
            // Create TCP messaging
            IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();

            Worker4504_OutputChannel = aMessaging.CreateDuplexOutputChannel("tcp://" + serverIP.Text + ":4504/");

            // Subscribe to response messages.
            Worker4504_OutputChannel.ConnectionClosed        += Worker4504_ConnectionClosed;
            Worker4504_OutputChannel.ConnectionOpened        += Worker4504_ConnectionOpened;
            Worker4504_OutputChannel.ResponseMessageReceived += Worker4504_ResponseMessageReceived;

            // Open connection and be able to send messages and receive response messages.
            Worker4504_OutputChannel.OpenConnection();

            if (Worker4504_OutputChannel.IsConnected)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public virtual void AuthenticationCancelledByClient()
        {
            IDuplexInputChannel  anInputChannel  = MessagingSystemFactory.CreateDuplexInputChannel(ChannelId);
            IDuplexOutputChannel anOutputChannel = MessagingSystemFactory.CreateDuplexOutputChannel(ChannelId);

            try
            {
                myClientCancelAuthentication = true;

                anInputChannel.StartListening();

                Exception anException = null;
                try
                {
                    // Client opens the connection.
                    anOutputChannel.OpenConnection();
                }
                catch (Exception err)
                {
                    anException = err;
                }

                Assert.IsInstanceOf <InvalidOperationException>(anException);

                // Check that the AuthenticationCancelled calleback was called.
                Assert.IsTrue(myAuthenticationCancelled);
            }
            finally
            {
                myClientCancelAuthentication = false;
                myAuthenticationCancelled    = false;

                anOutputChannel.CloseConnection();
                anInputChannel.StopListening();
            }
        }
예제 #22
0
        private bool Worker4504_Initialize()
        {
            // Create TCP messaging
            IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();
            Worker4504_OutputChannel = aMessaging.CreateDuplexOutputChannel("tcp://" + serverIP.Text + ":4504/");

            // Subscribe to response messages.
            Worker4504_OutputChannel.ConnectionClosed += Worker4504_ConnectionClosed;
            Worker4504_OutputChannel.ConnectionOpened += Worker4504_ConnectionOpened;
            Worker4504_OutputChannel.ResponseMessageReceived += Worker4504_ResponseMessageReceived;

            // Open connection and be able to send messages and receive response messages.
            Worker4504_OutputChannel.OpenConnection();

            if (Worker4504_OutputChannel.IsConnected)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
예제 #23
0
        public void A16_RequestResponse_100_ConstantlyInterrupted()
        {
            IDuplexOutputChannel aDuplexOutputChannel           = MessagingSystem.CreateDuplexOutputChannel(ChannelId);
            IDuplexInputChannel  aDuplexInputChannel            = MessagingSystem.CreateDuplexInputChannel(ChannelId);
            IDuplexInputChannel  anUnderlyingDuplexInputChannel = aDuplexInputChannel.GetField <IDuplexInputChannel>("myInputChannel");

            Assert.NotNull(anUnderlyingDuplexInputChannel);

            AutoResetEvent anAllMessagesProcessedEvent = new AutoResetEvent(false);

            // Received messages.
            List <int> aReceivedMessages = new List <int>();

            aDuplexInputChannel.MessageReceived += (x, y) =>
            {
                lock (aReceivedMessages)
                {
                    string aReceivedMessage = y.Message as string;

                    EneterTrace.Info("Received message: " + aReceivedMessage);

                    int k = int.Parse(aReceivedMessage);
                    aReceivedMessages.Add(k);
                    k += 1000;

                    EneterTrace.Info("Sent response message: " + k.ToString());
                    aDuplexInputChannel.SendResponseMessage(y.ResponseReceiverId, k.ToString());
                }
            };

            aDuplexOutputChannel.ConnectionClosed += (x, y) =>
            {
                EneterTrace.Info("ConnectionClosed invoked in duplex output channel");

                // The buffered duplex output channel exceeded the max offline time.
                anAllMessagesProcessedEvent.Set();
            };

            // Received response messages.
            List <int> aReceivedResponseMessages = new List <int>();

            aDuplexOutputChannel.ResponseMessageReceived += (x, y) =>
            {
                lock (aReceivedResponseMessages)
                {
                    string aReceivedMessage = y.Message as string;

                    EneterTrace.Info("Received response message: " + aReceivedMessage);

                    int k = int.Parse(aReceivedMessage);
                    aReceivedResponseMessages.Add(k);

                    if (aReceivedResponseMessages.Count == 100)
                    {
                        anAllMessagesProcessedEvent.Set();
                    }
                }
            };


            try
            {
                bool aTestFinishedFlag = false;

                aDuplexInputChannel.StartListening();
                aDuplexOutputChannel.OpenConnection();


                Thread anInteruptingThread = new Thread(() =>
                {
                    for (int i = 0; i < 100 && !aTestFinishedFlag; ++i)
                    {
                        anUnderlyingDuplexInputChannel.DisconnectResponseReceiver(aDuplexOutputChannel.ResponseReceiverId);
                        Thread.Sleep(ConnectionInterruptionFrequency);
                    }
                });

                // Start constant disconnecting.
                anInteruptingThread.Start();

                for (int i = 0; i < 100; ++i)
                {
                    aDuplexOutputChannel.SendMessage(i.ToString());
                }

                // Wait until all messages are processed.
                //anAllMessagesProcessedEvent.WaitOne();
                Assert.IsTrue(anAllMessagesProcessedEvent.WaitOne(20000), "The timeout occured.");

                aTestFinishedFlag = true;
                anInteruptingThread.Join();
            }
            finally
            {
                aDuplexOutputChannel.CloseConnection();
                aDuplexInputChannel.StopListening();
            }

            aReceivedMessages.Sort();
            Assert.AreEqual(100, aReceivedMessages.Count);
            for (int i = 0; i < 100; ++i)
            {
                Assert.AreEqual(i, aReceivedMessages[i]);
            }

            aReceivedResponseMessages.Sort();
            Assert.AreEqual(100, aReceivedResponseMessages.Count);
            for (int i = 0; i < 100; ++i)
            {
                Assert.AreEqual(i + 1000, aReceivedResponseMessages[i]);
            }
        }
예제 #24
0
        public void LoadBalancerConnectionLogic()
        {
            IMessagingSystemFactory aMessaging = new SynchronousMessagingSystemFactory();

            string aReceiverChannelId = "";
            EventHandler <DuplexChannelMessageEventArgs> aRequestReceived = (x, y) =>
            {
                // Echo the message.
                IDuplexInputChannel anInputChannel = (IDuplexInputChannel)x;
                aReceiverChannelId = anInputChannel.ChannelId;
                anInputChannel.SendResponseMessage(y.ResponseReceiverId, y.Message);
            };

            string aResponseReceiverId = "";
            ResponseReceiverEventArgs aDisconnectedLoadBalancerConnection      = null;
            EventHandler <ResponseReceiverEventArgs> aDisconnectedFromReceiver = (x, y) =>
            {
                aResponseReceiverId = ((IDuplexInputChannel)x).ChannelId;
                aDisconnectedLoadBalancerConnection = y;
            };

            // Receivers.
            IDuplexInputChannel[] aReceivers = new IDuplexInputChannel[3];
            for (int i = 0; i < aReceivers.Length; ++i)
            {
                aReceivers[i] = aMessaging.CreateDuplexInputChannel((i + 1).ToString());
                aReceivers[i].MessageReceived += aRequestReceived;
                aReceivers[i].ResponseReceiverDisconnected += aDisconnectedFromReceiver;
            }

            // Clients.
            IDuplexOutputChannel aClient1 = aMessaging.CreateDuplexOutputChannel("LB");
            string aReceivedResponse1     = "";

            aClient1.ResponseMessageReceived += (x, y) =>
            {
                aReceivedResponse1 = (string)y.Message;
            };

            IDuplexOutputChannel aClient2 = aMessaging.CreateDuplexOutputChannel("LB");
            string aReceivedResponse2     = "";

            aClient2.ResponseMessageReceived += (x, y) =>
            {
                aReceivedResponse2 = (string)y.Message;
            };


            // Load Balancer
            ILoadBalancerFactory aLoadBalancerFactory = new RoundRobinBalancerFactory(aMessaging);
            ILoadBalancer        aLoadBalancer        = aLoadBalancerFactory.CreateLoadBalancer();

            AutoResetEvent aReceiverRemovedEvent = new AutoResetEvent(false);
            string         aRemovedReceiverId    = "";

            aLoadBalancer.RequestReceiverRemoved += (x, y) =>
            {
                aRemovedReceiverId = y.ChannelId;
                aReceiverRemovedEvent.Set();
            };



            try
            {
                // Receivers start listening.
                foreach (IDuplexInputChannel aReceiver in aReceivers)
                {
                    aReceiver.StartListening();
                }

                // Load Balancer starts listening.
                for (int i = 0; i < aReceivers.Length; ++i)
                {
                    aLoadBalancer.AddDuplexOutputChannel((i + 1).ToString());
                }
                aLoadBalancer.AttachDuplexInputChannel(aMessaging.CreateDuplexInputChannel("LB"));

                // Clients connect the load balancer.
                aClient1.OpenConnection();
                aClient2.OpenConnection();

                // It shall use the next (second) receiver.
                aClient1.SendMessage("Hello.");
                Assert.AreEqual("Hello.", aReceivedResponse1);
                Assert.AreEqual("", aReceivedResponse2);
                Assert.AreEqual("2", aReceiverChannelId);
                aReceivedResponse1 = "";
                aReceivedResponse2 = "";

                // It shall use the next (third) receiver.
                aClient2.SendMessage("Hello.");
                Assert.AreEqual("", aReceivedResponse1);
                Assert.AreEqual("Hello.", aReceivedResponse2);
                Assert.AreEqual("3", aReceiverChannelId);
                aReceivedResponse1 = "";
                aReceivedResponse2 = "";

                // It is at the end of the pool so it shall starts from the beginning.
                aClient2.SendMessage("Hello.");
                Assert.AreEqual("", aReceivedResponse1);
                Assert.AreEqual("Hello.", aReceivedResponse2);
                Assert.AreEqual("1", aReceiverChannelId);
                aReceivedResponse1 = "";
                aReceivedResponse2 = "";

                // Let's remove the second receiver.
                aLoadBalancer.RemoveDuplexOutputChannel("2");
                Assert.IsNotNull(aDisconnectedLoadBalancerConnection);
                Assert.AreEqual("2", aResponseReceiverId);

                // The 2nd is removed so it shall use the 3rd one.
                aClient2.SendMessage("Hello.");
                Assert.AreEqual("", aReceivedResponse1);
                Assert.AreEqual("Hello.", aReceivedResponse2);
                Assert.AreEqual("3", aReceiverChannelId);
                aReceivedResponse1 = "";
                aReceivedResponse2 = "";

                // 1st receiver stops to listen.
                aReceivers[0].StopListening();

                // It should start from the beginnng but 1st is not listening and 2nd was removed.
                // So it shall use the 3rd one.
                aClient1.SendMessage("Hello.");
                Assert.AreEqual("Hello.", aReceivedResponse1);
                Assert.AreEqual("", aReceivedResponse2);
                Assert.AreEqual("3", aReceiverChannelId);
                aReceivedResponse1 = "";
                aReceivedResponse2 = "";

                aReceiverRemovedEvent.WaitOne();
                Assert.AreEqual("1", aRemovedReceiverId);


                aReceivers[2].StopListening();

                aClient2.SendMessage("Hello.");
                Assert.AreEqual("", aReceivedResponse1);
                Assert.AreEqual("", aReceivedResponse2);
                aReceivedResponse1 = "";
                aReceivedResponse2 = "";

                aReceiverRemovedEvent.WaitOne();
                Assert.AreEqual("3", aRemovedReceiverId);

                aReceivers[0].StartListening();
                aReceivers[2].StartListening();

                for (int i = 0; i < aReceivers.Length; ++i)
                {
                    aLoadBalancer.AddDuplexOutputChannel((i + 1).ToString());
                }

                aClient2.SendMessage("Hello.");
                Assert.AreEqual("", aReceivedResponse1);
                Assert.AreEqual("Hello.", aReceivedResponse2);
                Assert.AreEqual("2", aReceiverChannelId);
                aReceivedResponse1 = "";
                aReceivedResponse2 = "";
            }
            finally
            {
                aClient1.CloseConnection();
                aClient2.CloseConnection();
                aLoadBalancer.DetachDuplexInputChannel();
                foreach (IDuplexInputChannel aReceiver in aReceivers)
                {
                    aReceiver.StopListening();
                }
            }
        }
        private bool InitializeWorkerConnection()
        {
            // Create TCP messaging
            IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();
            Worker4504OutputChannel = aMessaging.CreateDuplexOutputChannel("tcp://127.0.0.1:4504/");

            // Subscribe to response messages.
            Worker4504OutputChannel.ConnectionClosed += Worker4504OutputChannel_ConnectionClosed;
            Worker4504OutputChannel.ConnectionOpened += Worker4504OutputChannel_ConnectionOpened;
            Worker4504OutputChannel.ResponseMessageReceived += Worker4504OutputChannel_ResponseMessageReceived;

            // Open connection and be able to send messages and receive response messages.
            Worker4504OutputChannel.OpenConnection();
            Log("Channel id : " + Worker4504OutputChannel.ChannelId);

            // Send a message.
            byte[] data = new byte[1048576]; // initialize 1MB data
            //byte[] data = new byte[10]; // initialize 1MB data
            Random random = new Random();
            random.NextBytes(data);
            Worker4504OutputChannel.SendMessage(data);
            Log("Sent data length : " + data.Length);

            // Close connection.
            //Worker4504OutputChannel.CloseConnection();

            return true;
        }
예제 #26
0
        // A message from a client is received. It must be forwarded to a request receiver from the pool.
        protected override void OnRequestMessageReceived(object sender, DuplexChannelMessageEventArgs e)
        {
            using (EneterTrace.Entering())
            {
                while (true)
                {
                    string aChannelId;

                    // Get the next available receiver.
                    using (ThreadLock.Lock(myReceiverManipulatorLock))
                    {
                        if (myAvailableReceivers.Count == 0)
                        {
                            EneterTrace.Error(TracedObject + "failed to forward the message because there no receivers in the pool.");
                            break;
                        }

                        // Move to the next receiver.
                        ++myCurrentAvailableReceiverIdx;
                        if (myCurrentAvailableReceiverIdx >= myAvailableReceivers.Count)
                        {
                            myCurrentAvailableReceiverIdx = 0;
                        }

                        aChannelId = myAvailableReceivers[myCurrentAvailableReceiverIdx];

                        // If there is not open connection for the current response receiver id, then open it.
                        TConnection aConnection = myOpenConnections.FirstOrDefault(x => x.ResponseReceiverId == e.ResponseReceiverId && x.DuplexOutputChannel.ChannelId == aChannelId);
                        if (aConnection == null)
                        {
                            IDuplexOutputChannel anOutputChannel = myOutputMessagingFactory.CreateDuplexOutputChannel(aChannelId);
                            anOutputChannel.ResponseMessageReceived += OnResponseMessageReceived;
                            anOutputChannel.ConnectionClosed        += OnRequestReceiverClosedConnection;

                            try
                            {
                                anOutputChannel.OpenConnection();
                            }
                            catch (Exception err)
                            {
                                EneterTrace.Warning(TracedObject + ErrorHandler.FailedToOpenConnection, err);

                                anOutputChannel.ResponseMessageReceived -= OnResponseMessageReceived;
                                anOutputChannel.ConnectionClosed        -= OnRequestReceiverClosedConnection;

                                // It was not possible to open the connection with the given receiver.
                                // So remove the receiver from available receivers.
                                myAvailableReceivers.Remove(aChannelId);

                                NotifyRequestRecieverRemoved(aChannelId);

                                // Continue with the next receiver.
                                continue;
                            }

                            aConnection = new TConnection(e.ResponseReceiverId, e.SenderAddress, anOutputChannel);
                            myOpenConnections.Add(aConnection);
                        }


                        // Try to forward the message via the connection.
                        try
                        {
                            aConnection.DuplexOutputChannel.SendMessage(e.Message);
                        }
                        catch (Exception err)
                        {
                            EneterTrace.Warning(TracedObject + ErrorHandler.FailedToSendMessage, err);

                            try
                            {
                                // Remove the connection.
                                aConnection.DuplexOutputChannel.CloseConnection();
                            }
                            catch (Exception err2)
                            {
                                EneterTrace.Warning(TracedObject + ErrorHandler.FailedToCloseConnection, err2);
                            }

                            aConnection.DuplexOutputChannel.ResponseMessageReceived -= OnResponseMessageReceived;
                            aConnection.DuplexOutputChannel.ConnectionClosed        -= OnRequestReceiverClosedConnection;

                            myOpenConnections.Remove(aConnection);

                            // Try next receiver.
                            continue;
                        }

                        break;
                    }
                }
            }
        }
예제 #27
0
        public void A01_SimpleRequestResponse()
        {
            IDuplexOutputChannel aDuplexOutputChannel = MessagingSystem.CreateDuplexOutputChannel(ChannelId);
            IDuplexInputChannel  aDuplexInputChannel  = MessagingSystem.CreateDuplexInputChannel(ChannelId);


            // Received messages.
            List <int> aReceivedMessages = new List <int>();

            aDuplexInputChannel.MessageReceived += (x, y) =>
            {
                //EneterTrace.Info("Message Received");
                lock (aReceivedMessages)
                {
                    string aReceivedMessage = y.Message as string;

                    int k = int.Parse(aReceivedMessage);
                    aReceivedMessages.Add(k);
                    k += 1000;

                    aDuplexInputChannel.SendResponseMessage(y.ResponseReceiverId, k.ToString());
                }
            };

            // Received response messages.
            List <int>     aReceivedResponseMessages   = new List <int>();
            AutoResetEvent anAllMessagesProcessedEvent = new AutoResetEvent(false);

            aDuplexOutputChannel.ResponseMessageReceived += (x, y) =>
            {
                //EneterTrace.Info("Response Received");
                lock (aReceivedResponseMessages)
                {
                    string aReceivedMessage = y.Message as string;

                    int k = int.Parse(aReceivedMessage);
                    aReceivedResponseMessages.Add(k);

                    if (k == 1019)
                    {
                        anAllMessagesProcessedEvent.Set();
                    }
                }
            };


            try
            {
                aDuplexInputChannel.StartListening();
                aDuplexOutputChannel.OpenConnection();

                for (int i = 0; i < 20; ++i)
                {
                    aDuplexOutputChannel.SendMessage(i.ToString());
                }

                // Wait untill all messages are processed.
                anAllMessagesProcessedEvent.WaitOne();
            }
            finally
            {
                aDuplexOutputChannel.CloseConnection();
                aDuplexInputChannel.StopListening();
            }

            aReceivedMessages.Sort();
            Assert.AreEqual(20, aReceivedMessages.Count);
            for (int i = 0; i < 20; ++i)
            {
                Assert.AreEqual(i, aReceivedMessages[i]);
            }

            aReceivedResponseMessages.Sort();
            Assert.AreEqual(20, aReceivedResponseMessages.Count);
            for (int i = 0; i < 20; ++i)
            {
                Assert.AreEqual(i + 1000, aReceivedResponseMessages[i]);
            }
        }
예제 #28
0
        public void B01_InactivityTimeout()
        {
            // Set the polling frequency slower
            // than inactivity timeout in the duplex input channel.
            // Therefore the timeout should occur before the polling - this is how the
            // inactivity is simulated in this test.
            IMessagingSystemFactory aMessagingSystem = new HttpMessagingSystemFactory(3000, 2000);

            IDuplexOutputChannel anOutputChannel1 = aMessagingSystem.CreateDuplexOutputChannel(ChannelId);
            IDuplexOutputChannel anOutputChannel2 = aMessagingSystem.CreateDuplexOutputChannel(ChannelId);

            IDuplexInputChannel anInputChannel = aMessagingSystem.CreateDuplexInputChannel(ChannelId);

            AutoResetEvent aConncetionEvent    = new AutoResetEvent(false);
            AutoResetEvent aDisconncetionEvent = new AutoResetEvent(false);

            List <TConnectionEvent> aConnections = new List <TConnectionEvent>();

            anInputChannel.ResponseReceiverConnected += (x, y) =>
            {
                aConnections.Add(new TConnectionEvent(DateTime.Now, y.ResponseReceiverId));
                aConncetionEvent.Set();
            };

            List <TConnectionEvent> aDisconnections = new List <TConnectionEvent>();

            anInputChannel.ResponseReceiverDisconnected += (x, y) =>
            {
                aDisconnections.Add(new TConnectionEvent(DateTime.Now, y.ResponseReceiverId));
                aDisconncetionEvent.Set();
            };

            try
            {
                anInputChannel.StartListening();
                Assert.IsTrue(anInputChannel.IsListening);

                // Create the 1st connection.
                anOutputChannel1.OpenConnection();
                Assert.IsTrue(anOutputChannel1.IsConnected);
                aConncetionEvent.WaitOne();
                Assert.AreEqual(1, aConnections.Count);
                Assert.IsFalse(string.IsNullOrEmpty(aConnections[0].ReceiverId));

                Thread.Sleep(1000);

                // Create the 2nd connection.
                anOutputChannel2.OpenConnection();
                Assert.IsTrue(anOutputChannel2.IsConnected);
                aConncetionEvent.WaitOne();
                Assert.AreEqual(2, aConnections.Count);
                Assert.IsFalse(string.IsNullOrEmpty(aConnections[1].ReceiverId));

                // Wait for the 1st disconnection
                aDisconncetionEvent.WaitOne();

                Assert.AreEqual(1, aDisconnections.Count);
                Assert.AreEqual(aConnections[0].ReceiverId, aDisconnections[0].ReceiverId);
                Assert.IsTrue(aDisconnections[0].Time - aConnections[0].Time > TimeSpan.FromMilliseconds(1900));

                // Wait for the 2nd disconnection
                aDisconncetionEvent.WaitOne();

                Assert.AreEqual(2, aDisconnections.Count);
                Assert.AreEqual(aConnections[1].ReceiverId, aDisconnections[1].ReceiverId);
                Assert.IsTrue(aDisconnections[1].Time - aConnections[1].Time > TimeSpan.FromMilliseconds(1900));
            }
            finally
            {
                anOutputChannel1.CloseConnection();
                anOutputChannel2.CloseConnection();
                anInputChannel.StopListening();
            }
        }
        protected override void OnRequestMessageReceived(object sender, DuplexChannelMessageEventArgs e)
        {
            using (EneterTrace.Entering())
            {
                WrappedData aWrappedData = null;

                try
                {
                    ISerializer aSerializer = mySerializer.ForResponseReceiver(e.ResponseReceiverId);

                    // Unwrap the incoming message.
                    aWrappedData = DataWrapper.Unwrap(e.Message, aSerializer);
                }
                catch (Exception err)
                {
                    EneterTrace.Error(TracedObject + "failed to unwrap the message.", err);
                    return;
                }

                // WrappedData.AddedData represents the channel id.
                // Therefore if everything is ok then it must be string.
                if (aWrappedData.AddedData is string)
                {
                    string aMessageReceiverId = (string)aWrappedData.AddedData;

                    TDuplexConnection aConectionToOutput = null;

                    // Try to find if the output channel with the required channel id and for the incoming response receiver
                    // already exists.
                    using (ThreadLock.Lock(myConnections))
                    {
                        aConectionToOutput = myConnections.FirstOrDefault(x => x.DuplexOutputChannel.ChannelId == aMessageReceiverId && x.ResponseReceiverId == e.ResponseReceiverId);

                        // If it does not exist then create the duplex output channel and open connection.
                        if (aConectionToOutput == null)
                        {
                            IDuplexOutputChannel aDuplexOutputChannel = null;

                            try
                            {
                                aDuplexOutputChannel = myOutputMessagingFactory.CreateDuplexOutputChannel(aMessageReceiverId);
                                aDuplexOutputChannel.ResponseMessageReceived += OnResponseMessageReceived;
                                aDuplexOutputChannel.OpenConnection();
                            }
                            catch (Exception err)
                            {
                                EneterTrace.Error(TracedObject + "failed to create and connect the duplex output channel '" + aMessageReceiverId + "'", err);

                                if (aDuplexOutputChannel != null)
                                {
                                    aDuplexOutputChannel.ResponseMessageReceived -= OnResponseMessageReceived;
                                    aDuplexOutputChannel.CloseConnection();
                                    aDuplexOutputChannel = null;
                                }
                            }

                            if (aDuplexOutputChannel != null)
                            {
                                aConectionToOutput = new TDuplexConnection(e.ResponseReceiverId, aDuplexOutputChannel);
                                myConnections.Add(aConectionToOutput);
                            }
                        }
                    }

                    if (aConectionToOutput != null)
                    {
                        try
                        {
                            // Send the unwrapped message.
                            aConectionToOutput.DuplexOutputChannel.SendMessage(aWrappedData.OriginalData);
                        }
                        catch (Exception err)
                        {
                            EneterTrace.Error(TracedObject + "failed to send the message to the output channel '" + aConectionToOutput.DuplexOutputChannel.ChannelId + "'.", err);
                        }
                    }
                }
                else
                {
                    EneterTrace.Error(TracedObject + "detected that the unwrapped message contian the channel id as the string type.");
                }
            }
        }
예제 #30
0
        private void ConnectHalovisionDevice()
        {
            try
            {
                Core.Initialize();

                if (txtDeviceURL.Text.Contains("://"))
                {
                    libvlc = new LibVLC(enableDebugLogs: true);
                    libvlc.SetLogFile($"{lucidScribeDataPath}\\vlc.log");

                    using (Media media = new Media(libvlc, txtDeviceURL.Text, FromType.FromLocation))
                    {
                        player      = new MediaPlayer(media);
                        player.Hwnd = pbDisplay.Handle;
                        player.Play();
                    }
                    return;
                }

                libvlc = new LibVLC(enableDebugLogs: false, "--rtsp-tcp");

                // Use TCP messaging.
                videoChannel = new TcpMessagingSystemFactory().CreateDuplexOutputChannel("tcp://" + txtDeviceURL.Text + ":8093/");
                videoChannel.ResponseMessageReceived += OnResponseMessageReceived;

                // Use unique name for the pipe.
                string aVideoPipeName = Guid.NewGuid().ToString();

                // Open pipe that will be read by VLC.
                videoPipe = new NamedPipeServerStream(@"\" + aVideoPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, 65528);
                ManualResetEvent vlcConnectedPipe = new ManualResetEvent(false);
                ThreadPool.QueueUserWorkItem(x =>
                {
                    videoPipe.WaitForConnection();

                    // Indicate VLC has connected the pipe.
                    vlcConnectedPipe.Set();
                });

                // VLC connects the pipe and starts playing.
                using (Media media = new Media(libvlc, @"stream://\\\.\pipe\" + aVideoPipeName, FromType.FromLocation))
                {
                    // Setup VLC so that it can process raw h264 data
                    media.AddOption(":demux=H264");

                    player      = new MediaPlayer(media);
                    player.Hwnd = pbDisplay.Handle;

                    // Note: This will connect the pipe and read the video.
                    player.Play();
                }

                // Wait until VLC connects the pipe so that it is ready to receive the stream.
                if (!vlcConnectedPipe.WaitOne(5000))
                {
                    throw new TimeoutException($"VLC did not open connection with {txtDeviceURL.Text}.");
                }

                // Open connection with service running on Raspberry.
                videoChannel.OpenConnection();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "LucidScribe.InitializePlugin()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #31
0
        public void A01_Reconnect_DisconnectReceiver()
        {
            IDuplexInputChannel  aDuplexInputChannel  = MessagingSystemFactory.CreateDuplexInputChannel(ChannelId);
            IDuplexOutputChannel aDuplexOutputChannel = MessagingSystemFactory.CreateDuplexOutputChannel(ChannelId);

            Reconnecter aReconnecter = new Reconnecter(aDuplexOutputChannel, TimeSpan.FromMilliseconds(300), -1);

            AutoResetEvent         aReconnectEvent     = new AutoResetEvent(false);
            DuplexChannelEventArgs aReconnectEventArgs = null;

            aReconnecter.ConnectionOpened += (x, y) =>
            {
                aReconnectEventArgs = y;
                aReconnectEvent.Set();
            };

            AutoResetEvent         aDisconnectEvent     = new AutoResetEvent(false);
            DuplexChannelEventArgs aDisconnectEventArgs = null;

            aReconnecter.ConnectionClosed += (x, y) =>
            {
                aDisconnectEventArgs = y;
                aDisconnectEvent.Set();
            };


            AutoResetEvent aConnectionOpenedEvent = new AutoResetEvent(false);

            aDuplexOutputChannel.ConnectionOpened += (x, y) =>
            {
                aConnectionOpenedEvent.Set();
            };

            AutoResetEvent aConnectionClosedEvent = new AutoResetEvent(false);

            aDuplexOutputChannel.ConnectionClosed += (x, y) =>
            {
                aConnectionClosedEvent.Set();
            };

            try
            {
                aReconnecter.EnableReconnecting();

                // Start listening.
                aDuplexInputChannel.StartListening();
                aDuplexOutputChannel.OpenConnection();
                Thread.Sleep(2000);

                Assert.IsTrue(aDuplexOutputChannel.IsConnected);
                aConnectionOpenedEvent.WaitOne();

                // Disconnect the duplexoutput channel.
                aDuplexInputChannel.DisconnectResponseReceiver(aDuplexOutputChannel.ResponseReceiverId);

                // Wait until the disconnect is notified.
                aDisconnectEvent.WaitOne();
                aConnectionClosedEvent.WaitOne();

                Assert.AreEqual(aDuplexOutputChannel.ChannelId, aDisconnectEventArgs.ChannelId);
                Assert.AreEqual(aDuplexOutputChannel.ResponseReceiverId, aDisconnectEventArgs.ResponseReceiverId);

                // Wait until the reconnecter opens connection again.
                aReconnectEvent.WaitOne();
                Assert.AreEqual(aDuplexOutputChannel.ChannelId, aReconnectEventArgs.ChannelId);
                Assert.AreEqual(aDuplexOutputChannel.ResponseReceiverId, aReconnectEventArgs.ResponseReceiverId);

                Assert.IsTrue(aDuplexOutputChannel.IsConnected);

                aConnectionOpenedEvent.WaitOne();
            }
            finally
            {
                aReconnecter.DisableReconnecting();
                aDuplexOutputChannel.CloseConnection();
                aDuplexInputChannel.StopListening();
            }
        }
예제 #32
0
        public void A02_Reconnect_StopListening()
        {
            MonitoredMessagingFactory aConnectionMonitor = new MonitoredMessagingFactory(MessagingSystemFactory);

            IDuplexInputChannel  aDuplexInputChannel  = aConnectionMonitor.CreateDuplexInputChannel(ChannelId);
            IDuplexOutputChannel aDuplexOutputChannel = aConnectionMonitor.CreateDuplexOutputChannel(ChannelId);

            // Max 5 attempts to try to reconnect.
            Reconnecter aReconnecter = new Reconnecter(aDuplexOutputChannel, TimeSpan.FromMilliseconds(300), 5);

            AutoResetEvent         aReconnectEvent     = new AutoResetEvent(false);
            DuplexChannelEventArgs aReconnectEventArgs = null;

            aReconnecter.ConnectionOpened += (x, y) =>
            {
                aReconnectEventArgs = y;
                aReconnectEvent.Set();
            };

            AutoResetEvent         aDisconnectEvent     = new AutoResetEvent(false);
            DuplexChannelEventArgs aDisconnectEventArgs = null;

            aReconnecter.ConnectionClosed += (x, y) =>
            {
                aDisconnectEventArgs = y;
                aDisconnectEvent.Set();
            };

            AutoResetEvent         aReconnecFailedEvent         = new AutoResetEvent(false);
            DuplexChannelEventArgs aReconnectingFailedEventArgs = null;

            aReconnecter.ReconnectingFailed += (x, y) =>
            {
                aReconnectingFailedEventArgs = y;
                aReconnecFailedEvent.Set();
            };

            try
            {
                aReconnecter.EnableReconnecting();

                // Start listening.
                aDuplexInputChannel.StartListening();
                aDuplexOutputChannel.OpenConnection();
                Thread.Sleep(2000);

                Assert.IsTrue(aDuplexOutputChannel.IsConnected);
                Assert.IsNull(aReconnectingFailedEventArgs);
                Assert.IsNull(aDisconnectEventArgs);
                Assert.IsNull(aReconnectEventArgs);


                // Stop listening.
                // Note: The Reconnecter will try 5 times to reopen the connection, then it will notify, the reconnecion failed.
                aDuplexInputChannel.StopListening();

                // Wait until the disconnect is notified.
                aDisconnectEvent.WaitOne();
                Assert.AreEqual(aDuplexOutputChannel.ChannelId, aDisconnectEventArgs.ChannelId);
                Assert.AreEqual(aDuplexOutputChannel.ResponseReceiverId, aDisconnectEventArgs.ResponseReceiverId);
                Assert.IsFalse(aDuplexOutputChannel.IsConnected);
                Assert.IsNull(aReconnectEventArgs);

                // Wait until the reconnect fails after 5 failed reconnects.
                aReconnecFailedEvent.WaitOne();
                Assert.AreEqual(aDuplexOutputChannel.ChannelId, aReconnectingFailedEventArgs.ChannelId);
                Assert.AreEqual(aDuplexOutputChannel.ResponseReceiverId, aReconnectingFailedEventArgs.ResponseReceiverId);
                Assert.IsFalse(aDuplexOutputChannel.IsConnected);
                Assert.IsNull(aReconnectEventArgs);
            }
            finally
            {
                aDuplexOutputChannel.CloseConnection();
                aDuplexInputChannel.StopListening();
                aReconnecter.DisableReconnecting();
            }
        }