예제 #1
0
        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            long idleTime = TCPUtils.ElapsedSecondsSince(ConnectionIdleTimer);

            Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                              e.SignalTime);
            Console.WriteLine("The connection has been idle {0} seconds", idleTime);
            try
            {
                if (idleTime > idleTimeout)
                {
                    Console.WriteLine("The connection has been idle for longer than the maximum {0} seconds. Closing connection", idleTimeout);
                    StopTimer();
                    connectedSocket.Shutdown(SocketShutdown.Both);
                    connectedSocket.Close();
                    throw new System.Net.Sockets.SocketException(10060);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
예제 #2
0
        public static void Main()
        {
            // Set up the new connection factory and enable connection recovery with an interval of 20 seconds
            factory = new ConnectionFactory()
            {
                HostName = "helixlin1t.ynhh.org", UserName = "******", Password = "******", RequestedHeartbeat = 30
            };
            factory.AutomaticRecoveryEnabled = true;
            factory.NetworkRecoveryInterval  = TimeSpan.FromSeconds(20);


            // Try to connect to our RabbitMQ server, wait and retry if not successful
            Boolean rmqConnected = false;

            while (!rmqConnected)
            {
                try
                {
                    // factory = new ConnectionFactory() { HostName = "helixlin1t.ynhh.org" };
                    Console.WriteLine("\nTrying RabbitMQ Connection...");
                    connection   = factory.CreateConnection();
                    rmqConnected = true;
                }
                catch (Exception e)
                {
                    // Console.WriteLine("RMQ Connection attempt: Caught exception: " + e.ToString());
                    Console.WriteLine("RMQ Connection attempt: Caught Exception type: " + e.GetType().ToString());
                }
                if (!rmqConnected)
                {
                    // Wait "socktimeout" seconds and then we'll try again
                    DateTime timer = DateTime.Now;

                    while (TCPUtils.ElapsedSecondsSince(timer) < RMQConnectTimeout)
                    {
                        // elapsed = TCPUtils.ElapsedSecondsSince(timer);
                        // Console.WriteLine("Connect retry loop: elapsed seconds: " + elapsed.ToString());
                        Thread.Sleep(1000);
                        Console.Write(".");
                    }
                }
                else
                {
                    Console.WriteLine("Connected");
                }
            }

            // Now we have a connection to the ConnectionFactory. Set up the queue
            try
            {
                // using (connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    IBasicProperties props = channel.CreateBasicProperties();
                    props.DeliveryMode = 2; // persistent

                    channel.QueueDeclare(queue: "hello",
                                         durable: true,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);
                    channel.ModelShutdown += (model, ea) =>
                    {
                        Console.WriteLine(" [xx] queue producer shutdown detected");
                    };

                    while (true)
                    {
                        Console.Write("Enter the string to be queued (<enter> to exit): ");

                        String message = Console.ReadLine();
                        if (message.Length == 0)
                        {
                            break;
                        }
                        // string message = "Hello World!";
                        var body = Encoding.UTF8.GetBytes(message);

                        if (channel.IsOpen)
                        {
                            channel.BasicPublish(exchange: "",
                                                 routingKey: "hello",
                                                 basicProperties: props,
                                                 body: body);
                            Console.WriteLine(" [x] Sent {0}", message);
                        }
                        else
                        {
                            Console.WriteLine(" [xxx] Cannot send message on a closed channel; please try again.");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught exception: " + e.ToString());
                Console.WriteLine("Exception type: " + e.GetType().ToString());
            }


            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }
예제 #3
0
        public static void Main()
        {
            // Set up the new connection factory and enable connection recovery with an interval of 20 seconds
            factory = new ConnectionFactory()
            {
                HostName = "helixlin1t.ynhh.org", UserName = "******", Password = "******", RequestedHeartbeat = 30
            };
            factory.AutomaticRecoveryEnabled = true;
            factory.NetworkRecoveryInterval  = TimeSpan.FromSeconds(20);

            // Try to connect to our RabbitMQ server, wait and retry if not successful
            Boolean rmqConnected = false;

            while (!rmqConnected)
            {
                try
                {
                    // factory = new ConnectionFactory() { HostName = "helixlin1t.ynhh.org" };
                    Console.WriteLine("\nTrying RabbitMQ Connection...");
                    connection   = factory.CreateConnection();
                    rmqConnected = true;
                }
                catch (Exception e)
                {
                    // Console.WriteLine("RMQ Connection attempt: Caught exception: " + e.ToString());
                    Console.WriteLine("RMQ Connection attempt: Caught Exception type: " + e.GetType().ToString());
                }
                if (!rmqConnected)
                {
                    // Wait "socktimeout" seconds and then we'll try again
                    DateTime timer = DateTime.Now;

                    while (TCPUtils.ElapsedSecondsSince(timer) < RMQConnectTimeout)
                    {
                        // elapsed = TCPUtils.ElapsedSecondsSince(timer);
                        // Console.WriteLine("Connect retry loop: elapsed seconds: " + elapsed.ToString());
                        Thread.Sleep(1000);
                        Console.Write(".");
                    }
                }
                else
                {
                    Console.WriteLine("Connected");
                }
            }

            // Now we have a connection to the ConnectionFactory. Set up the queue
            try
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "hello",
                                         durable: true,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);

                    var consumer = new EventingBasicConsumer(channel);

                    consumer.Received += (model, ea) =>
                    {
                        var body = ea.Body;

                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine(" [x] Received {0}", message);
                    };
                    consumer.Shutdown += (model, ea) =>
                    {
                        Console.WriteLine(" [xx] Queue consumer shutdown detected");
                    };
                    channel.BasicConsume(queue: "hello", autoAck: true, consumer: consumer);

                    Console.WriteLine(" Press [enter] to exit.");
                    Console.ReadLine();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught exception: " + e.ToString());
                Console.WriteLine("Exception type: " + e.GetType().ToString());
            }


            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }
예제 #4
0
        // private static System.Timers.Timer aTimer;


        // private static void SetTimer()
        // {
        //   // Create a timer with a two second interval.
        //    aTimer = new System.Timers.Timer(10000);
        //    // Hook up the Elapsed event for the timer.
        //    aTimer.Elapsed += OnTimedEvent;
        //    aTimer.AutoReset = true;
        //    aTimer.Enabled = true;
        // }

        // private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        // {
        //     Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
        //                      e.SignalTime);
        //}

        public static void Main()
        {
            IPAddress myIP = TCPUtils.GetIPV4FromHostName(hostName);

            // // Start our timer which will interrupt us every ten seconds.
            // SetTimer();


            try
            {
                // Outer loop: we enter this loop without an instantiated TCPClient object. If we get back to the
                // top of the loop again it's because the client has been closed and we need to start it up again
                while (true)
                {
                    TcpClient tcpclnt = new TcpClient();
                    // Inner try clause. We want to intercept socket connection failures, try again after
                    // socktimeout seconds
                    while (!tcpclnt.Connected)
                    {
                        try
                        {
                            Console.WriteLine("Connecting to {0:S} on port {1:D}...", hostName, hostPort);
                            //Console.WriteLine("Connecting...");
                            tcpclnt.Connect(myIP, hostPort);
                        }
                        // Inner catch clause. We want to intercept socket connection failures here.
                        // But we are only catching socket exceptions; anything else will blow up the program
                        catch (SocketException e)
                        {
                            Console.WriteLine("Inner SocketException 1: " + e.ToString());
                            // Console.WriteLine("Exception: " + e.GetType().ToString());
                            // Console.WriteLine("Error..... " + e.StackTrace);
                        }
                        if (!tcpclnt.Connected)
                        {
                            // Wait "socktimeout" seconds and then we'll try again
                            DateTime timer = DateTime.Now;

                            while (TCPUtils.ElapsedSecondsSince(timer) < sockTimeout)
                            {
                                // elapsed = TCPUtils.ElapsedSecondsSince(timer);
                                // Console.WriteLine("Connect retry loop: elapsed seconds: " + elapsed.ToString());
                                Thread.Sleep(1000);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Connected");
                        }
                    } // while (!tcpclnt.connected)

                    // Loop until a null string is entered
                    while (true)
                    {
                        Console.Write("Enter the string to be transmitted : ");

                        String str = Console.ReadLine();
                        if (str.Length == 0)
                        {
                            break;
                        }
                        // add back the terminating newline that we'll use as end-of-record separator
                        str = str + "\n";

                        // Try clause for writing to and reading from the socket.
                        // Catch exceptions like other end closed
                        try
                        {
                            Stream stm = tcpclnt.GetStream();

                            ASCIIEncoding asen = new ASCIIEncoding();

                            // HACK: Add a prefix with no trailing record separator
                            string prefix = ":prefix:";
                            byte[] ba     = asen.GetBytes(prefix);
                            Console.WriteLine("Transmitting.....");

                            stm.Write(ba, 0, ba.Length);

                            // Now send the terminated string
                            //byte[] ba = asen.GetBytes(str);
                            ba = asen.GetBytes(str);
                            Console.WriteLine("Transmitting.....");

                            stm.Write(ba, 0, ba.Length);

                            // byte[] bb = new byte[100];
                            byte[] bb = new byte[100];
                            int    k  = stm.Read(bb, 0, 100);

                            for (int i = 0; i < k; i++)
                            {
                                Console.Write(Convert.ToChar(bb[i]));
                            }
                            Console.WriteLine("");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Inner Exception 2: " + e.ToString());
                            Console.WriteLine("Exception Type: " + e.GetType().ToString());
                            tcpclnt.Close();
                            break;
                        }
                    }
                    Console.WriteLine("Broke out of loop. Closing TCP client.");
                    tcpclnt.Close();
                } // while (true()
            }

            // We can have multiple catch clauses tailored to specific error conditions. These are all
            // redundant because they don't do anything specific to the type of exception being caught.
            catch (SocketException e)
            {
                Console.WriteLine("Outer Socket Exception: " + e.ToString());
                Console.WriteLine("Exception: " + e.GetType().ToString());
            }
            catch (IOException e)
            {
                Console.WriteLine("Outer IO Exception: " + e.ToString());
                Console.WriteLine("Exception: " + e.GetType().ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Outer General Exception: " + e.ToString());
                Console.WriteLine("Exception: " + e.GetType().ToString());
            }

            // // Clean up our timer
            // aTimer.Stop();
            // aTimer.Dispose();
        } // end public static void Main()