public QpidResourceHolder(IClientFactory connectionFactory, IClient connection, IClientSession channel)
 {
     this.clientFactory = connectionFactory;
     AddConnection(connection);
     AddChannel(channel);
     this.frozen = true;
 }
        public bool rcvMeta(IClientSession session, IMutableMessage message)
        {
            Dictionary<String, Object> ext = (Dictionary<String, Object>)message.getExt(false);
            if (ext != null)
            {
                Dictionary<String, Object> sync = (Dictionary<String, Object>)ext["timesync"];
                if (sync != null)
                {
                    long now = (System.DateTime.Now.Ticks - 621355968000000000) / 10000;

                    long tc = ObjectConverter.ToInt64(sync["tc"], 0);
                    long ts = ObjectConverter.ToInt64(sync["ts"], 0);
                    int p = ObjectConverter.ToInt32(sync["p"], 0);
                    // final int a=((Number)sync.get("a")).intValue();

                    int l2 = (int)((now - tc - p) / 2);
                    int o2 = (int)(ts - tc - l2);

                    _lag = _lag == 0 ? l2 : (_lag + l2) / 2;
                    _offset = _offset == 0 ? o2 : (_offset + o2) / 2;
                }
            }

            return true;
        }
Exemplo n.º 3
0
 internal void SignOut(IClientSession session)
 {
     if (_sessions.Remove(session))
     {
         if (_sessions.Count == 0)
             this.Status = ChatUserStatus.Offline;
         BroadcastStatus();
     }
 }
 public bool sendMeta(IClientSession session, IMutableMessage message)
 {
     Dictionary<String, Object> ext = (Dictionary<String, Object>)message.getExt(true);
     long now = (System.DateTime.Now.Ticks - 621355968000000000) / 10000;
     // Changed JSON.Literal to String
     String timesync = "{\"tc\":" + now + ",\"l\":" + _lag + ",\"o\":" + _offset + "}";
     ext["timesync"] = timesync;
     return true;
 }
Exemplo n.º 5
0
 private static void publishMessages(IClientSession session, string routing_key)
 {
     IMessage message = new Message();
     // Asynchronous transfer sends messages as quickly as
     // possible without waiting for confirmation.
     for (int i = 0; i < 10; i++)
     {
         message.ClearData();
         message.AppendData(Encoding.UTF8.GetBytes("Message " + i));
         session.MessageTransfer("amq.topic", routing_key, message);
     }
 }
Exemplo n.º 6
0
        public bool sendMeta(IClientSession session, IMutableMessage message)
        {
            if (Channel_Fields.META_HANDSHAKE.Equals(message.Channel))
            {
                message.getExt(true)[EXT_FIELD] = true;
                _ackId = -1;
            }
            else if (_serverSupportsAcks && Channel_Fields.META_CONNECT.Equals(message.Channel))
            {
                message.getExt(true)[EXT_FIELD] = _ackId;
            }

            return true;
        }
Exemplo n.º 7
0
        public bool SendMeta(IClientSession session, IMutableMessage message)
        {
            switch (message.Channel)
            {
            case ChannelFields.MetaHandshake:
                message.GetExt(true)[ExtField] = true;
                break;

            case ChannelFields.MetaSubscribe:
                message.GetExt(true)[ExtField] = new Dictionary <string, long>(_channelToReplayId);
                break;
            }

            return(true);
        }
Exemplo n.º 8
0
 public static void CloseChannel(IClientSession channel)
 {
     if (channel != null)
     {
         try
         {
             channel.Close();
         }
             //TODO should this really be trace level?
         catch (Exception ex)
         {
             logger.Debug("Unexpected exception on closing RabbitMQ Channel", ex);
         }
     }
 }
Exemplo n.º 9
0
        public static void Send(this IClientSession session, IPacket packet)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (packet == null)
            {
                throw new ArgumentNullException(nameof(packet));
            }

            var byteAryForMsg = packet.Data;

            session.Send(byteAryForMsg, 0, byteAryForMsg.Length);
        }
Exemplo n.º 10
0
 public static void CloseChannel(IClientSession channel)
 {
     if (channel != null)
     {
         try
         {
             channel.Close();
         }
         //TODO should this really be trace level?
         catch (Exception ex)
         {
             logger.Debug("Unexpected exception on closing RabbitMQ Channel", ex);
         }
     }
 }
Exemplo n.º 11
0
        // Clients

        public bool Login(IClientSession clientSession)
        {
            bool result;

            try
            {
                Store(clientSession);
                result = true;
            }
            catch (Exception)
            {
                result = false;
                //TODO: log exception
            }
            return(result);
        }
        public void BeginConnect(EndPoint serverEndPoint)
        {
            if (PipeLineProcessor == null)
                throw new Exception("This client has not been initialized.");

            m_Session = new AsyncTcpSession(serverEndPoint, 4096);
            m_Session.Connected += new EventHandler(m_Session_Connected);
            m_Session.Error += new EventHandler<ErrorEventArgs>(m_Session_Error);
            m_Session.Closed += new EventHandler(m_Session_Closed);
            m_Session.DataReceived += new EventHandler<DataEventArgs>(m_Session_DataReceived);

            if (ReceiveBufferSize > 0)
                m_Session.ReceiveBufferSize = ReceiveBufferSize;

            m_Session.Connect();
        }
Exemplo n.º 13
0
        // We need to add auth-headers etc...
        public HttpAppClient(IClientSession session, ILogger logger)
        {
            _session = session;
            _logger  = logger;
            _client  = new HttpClient();
            _client.DefaultRequestHeaders.Add("session-id", session.Id.ToString());

            buffer = new ActionBlock <IAggregateOperation> [16];
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = new ActionBlock <IAggregateOperation>(x => x.Run(), new ExecutionDataflowBlockOptions()
                {
                    EnsureOrdered = true
                });
            }
        }
Exemplo n.º 14
0
        public static void FromBytes(this IClientSession clientSession, byte[] buffer)
        {
            if (buffer == null)
            {
                return;
            }

            using (var inputStream = new MemoryStream(buffer))

                // using (var zippedStream = new GZipStream(inputStream, CompressionMode.Decompress))
                using (var streamReader = new StreamReader(inputStream))
                {
                    var settings = streamReader.ReadToEnd();
                    JsonConvert.PopulateObject(settings, clientSession);
                }
        }
Exemplo n.º 15
0
        public static byte[] ToBytes(this IClientSession clientSession)
        {
            using (var outputStream = new MemoryStream())

                // using (var zippedStream = new GZipStream(output, CompressionMode.Compress))
                using (var streamWriter = new StreamWriter(outputStream))
                    using (var jWriter = new JsonTextWriter(streamWriter))
                    {
                        var serializer = new JsonSerializer();
                        serializer.Serialize(jWriter, clientSession);
                        jWriter.Flush();
                        streamWriter.Flush();

                        return(outputStream.ToArray());
                    }
        }
Exemplo n.º 16
0
        private object InvokeOperation(IClientSession session, string operation, object parameter, Func <OperationWrapper, OperationContext, Object> resultFunc)
        {
            Assert.NullArgument(session, "session");
            Assert.EmptyString(operation, "operation");
            Assert.NullArgument(resultFunc, "resultFunc");
            OperationWrapper wrapper = null;

            if (_operations.TryGetValue(operation, out wrapper))
            {
                var context = new OperationContext(session, wrapper, parameter);
                return(resultFunc.Invoke(wrapper, context));
            }
            else
            {
                throw new PipelineException("Operation not found: ".Templ(operation));
            }
        }
Exemplo n.º 17
0
        private void SetSessionByUser(string login, IClientSession session, bool setting)
        {
            List <IClientSession> buffer = null;

            if (!_sessionsByUser.TryGetValue(login, out buffer))
            {
                buffer = _sessionsByUser[login] = new List <IClientSession>();
            }
            if (setting)
            {
                buffer.Add(session);
            }
            else
            {
                buffer.Remove(session);
            }
        }
Exemplo n.º 18
0
 public void SubscribeWithImage(List <string> topic, string svrId, string signalId)
 {
     if (topic == null || topic.Count == 0)
     {
         log.Warn("Topic is null,so can't subscribeWithImage!");
         return;
     }
     foreach (string t in topic)
     {
         topics.Add(new BaseDestination(t));
     }
     if (_conn != null && _conn.Connected)
     {
         _session = _conn.createSession();
         _session.subscribe(topics, svrId, signalId, this);
     }
 }
Exemplo n.º 19
0
        protected void TryToConnect()
        {
            reqsOutstanding = 1;
            Agent newAgent = new Agent(this, 0, "BrokerAgent");

            Agents.Add(newAgent.AgentKey(), newAgent);
            client = new Client();
            client.Connect(url.Hostname, url.Port, null, url.AuthName, url.AuthPassword);
            clientSession = client.CreateSession(timeout);
            //clientSession.SetAutoSync(false) ;
            string name = System.Text.Encoding.UTF8.GetString(clientSession.GetName());

            replyName = "reply-" + name;
            topicName = "topic-" + name;
            clientSession.SetAutoSync(true);
            Option[] options = new Option[] { Option.EXCLUSIVE, Option.AUTO_DELETE };

            // This queue is used for responses to messages which are sent.
            clientSession.QueueDeclare(replyName, options);
            clientSession.ExchangeBind(replyName, "amq.direct", replyName);
            clientSession.AttachMessageListener(this, "rdest");
            clientSession.MessageSubscribe(replyName, "rdest", MessageAcceptMode.NONE, MessageAcquireMode.PRE_ACQUIRED, null, 0, null);
            clientSession.MessageSetFlowMode("rdest", MessageFlowMode.WINDOW);
            clientSession.MessageFlow("rdest", MessageCreditUnit.BYTE, ClientSession.MESSAGE_FLOW_MAX_BYTES);
            clientSession.MessageFlow("rdest", MessageCreditUnit.MESSAGE, ClientSession.MESSAGE_FLOW_MAX_BYTES);

            // This queue is used for unsolicited messages sent to this class.
            clientSession.QueueDeclare(topicName, options);
            clientSession.AttachMessageListener(this, "tdest");
            clientSession.MessageSubscribe(topicName, "tdest", MessageAcceptMode.NONE, MessageAcquireMode.PRE_ACQUIRED, null, 0, null);
            clientSession.MessageSetFlowMode("tdest", MessageFlowMode.WINDOW);
            clientSession.MessageFlow("tdest", MessageCreditUnit.BYTE, ClientSession.MESSAGE_FLOW_MAX_BYTES);
            clientSession.MessageFlow("tdest", MessageCreditUnit.MESSAGE, ClientSession.MESSAGE_FLOW_MAX_BYTES);

            outSession = client.CreateSession(timeout);
            outSession.ExchangeBind(replyName, "amq.direct", replyName);

            connected = true;
            consoleSession.HandleBrokerConnect(this);


            IEncoder encoder = CreateEncoder();

            this.SetHeader(encoder, 'B', 0);
            this.Send(encoder);
        }
Exemplo n.º 20
0
 public void SendMessage(IClientSession session, string messageId, object data)
 {
     lock (__lockObject)
     {
         List <IPipelineMessageItem> buffer = null;
         if (!_messages.TryGetValue(session.SessionId, out buffer))
         {
             buffer = new List <IPipelineMessageItem>();
             _messages[session.SessionId] = buffer;
         }
         buffer.Insert(0, new MessageBufferItem(messageId, data));
         if (buffer.Count > 511)
         {
             buffer.RemoveAt(buffer.Count - 1);
         }
     }
 }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            string host        = ConfigurationManager.AppSettings["Host"];
            int    port        = int.Parse(ConfigurationManager.AppSettings["Port"]);
            string virtualhost = ConfigurationManager.AppSettings["VirtualHost"];
            string username    = ConfigurationManager.AppSettings["Username"];
            string password    = ConfigurationManager.AppSettings["Password"];

            Client connection = new Client();

            try
            {
                connection.Connect(host, port, virtualhost, username, password);
                IClientSession session = connection.CreateSession(50000);

                //--------- Main body of program --------------------------------------------

                // Unlike topic exchanges and direct exchanges, a fanout
                // exchange need not set a routing key.
                IMessage message = new Message();

                // Asynchronous transfer sends messages as quickly as
                // possible without waiting for confirmation.
                for (int i = 0; i < 10; i++)
                {
                    message.ClearData();
                    message.AppendData(Encoding.UTF8.GetBytes("Message " + i));
                    session.MessageTransfer("amq.fanout", message);
                }

                // And send a syncrhonous final message to indicate termination.
                message.ClearData();
                message.AppendData(Encoding.UTF8.GetBytes("That's all, folks!"));
                session.MessageTransfer("amq.fanout", message);
                session.Sync();

                //-----------------------------------------------------------------------------

                connection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: \n" + e.StackTrace);
            }
        }
        public Task<bool> ConnectAsync(EndPoint serverEndPoint)
        {
            if (PipeLineProcessor == null)
                throw new Exception("This client has not been initialized.");

            m_ConnectTaskSource = new TaskCompletionSource<bool>();
            m_Session = new AsyncTcpSession(serverEndPoint, 4096);
            m_Session.Connected += new EventHandler(m_Session_Connected);
            m_Session.Error += new EventHandler<ErrorEventArgs>(m_Session_Error);
            m_Session.Closed +=new EventHandler(m_Session_Closed);
            m_Session.DataReceived += new EventHandler<DataEventArgs>(m_Session_DataReceived);

            if (ReceiveBufferSize > 0)
                m_Session.ReceiveBufferSize = ReceiveBufferSize;

            m_Session.Connect();
            return m_ConnectTaskSource.Task;
        }
        public Task<bool> ConnectAsync(EndPoint serverEndPoint)
        {
            if (PipeLineProcessor == null)
                throw new Exception("This client has not been initialized.");

            m_ConnectTaskSource = new TaskCompletionSource<bool>();
            m_Session = new AsyncTcpSession(serverEndPoint, 4096);
            m_Session.Connected += new EventHandler(m_Session_Connected);
            m_Session.Error += new EventHandler<ErrorEventArgs>(m_Session_Error);
            m_Session.Closed +=new EventHandler(m_Session_Closed);
            m_Session.DataReceived += new EventHandler<DataEventArgs>(m_Session_DataReceived);

            if (ReceiveBufferSize > 0)
                m_Session.ReceiveBufferSize = ReceiveBufferSize;

            m_Session.Connect();
            return m_ConnectTaskSource.Task;
        }
Exemplo n.º 24
0
        public bool ReceiveMeta(IClientSession session, IMutableMessage message)
        {
            if (ChannelFields.META_HANDSHAKE.Equals(message.Channel))
            {
                var ext = (Dictionary <string, object>)message.GetExt(false);
                _serverSupportsAcks = ext != null && true.Equals(ext[EXT_FIELD]);
            }
            else if (_serverSupportsAcks && true.Equals(message[MessageFields.SUCCESSFUL_FIELD]) && ChannelFields.META_CONNECT.Equals(message.Channel))
            {
                var ext = (Dictionary <string, object>)message.GetExt(false);
                if (ext != null)
                {
                    ext.TryGetValue(EXT_FIELD, out var ack);
                    _ackId = ObjectConverter.ToInt32(ack, _ackId);
                }
            }

            return(true);
        }
Exemplo n.º 25
0
        public void Login()
        {
            using (var connector = new Connector())
            {
                IClientSession session = connector.Login("User1", "Machine1");
                Assert.IsNotNull(session);
                Assert.IsTrue(session.IsLoggedIn);
                Assert.AreEqual("User1", session.Name);
                Assert.AreEqual("Machine1", session.Endpoint);

                IClient client = connector.GetClient("User1");
                Assert.IsNotNull(client);
                Assert.AreEqual("User1", client.Name);
                Assert.AreEqual("Machine1", client.LastLoginEndpoint);

                session.Dispose();
                Assert.IsFalse(session.IsLoggedIn);
            }
        }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            string host        = ConfigurationManager.AppSettings["Host"];
            int    port        = int.Parse(ConfigurationManager.AppSettings["Port"]);
            string virtualhost = ConfigurationManager.AppSettings["VirtualHost"];
            string username    = ConfigurationManager.AppSettings["Username"];
            string password    = ConfigurationManager.AppSettings["Password"];

            Client connection = new Client();

            try
            {
                connection.Connect(host, port, virtualhost, username, password);
                IClientSession session = connection.CreateSession(50000);

                //--------- Main body of program --------------------------------------------
                // Create a request queue for clients to use when making
                // requests.
                const string request_queue = "request";
                // Use the name of the request queue as the routing key
                session.QueueDeclare(request_queue);
                session.ExchangeBind(request_queue, "amq.direct", request_queue);

                lock (session)
                {
                    // Create a listener and subscribe it to the request_queue
                    IMessageListener listener = new MessageListener(session);
                    session.AttachMessageListener(listener, request_queue);
                    session.MessageSubscribe(request_queue);
                    // Receive messages until all messages are received
                    Console.WriteLine("Waiting for requests");
                    Monitor.Wait(session);
                }

                //---------------------------------------------------------------------------

                connection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: \n" + e.StackTrace);
            }
        }
 public void AddChannel(IClientSession channel, IClient connection)
 {
     AssertUtils.IsTrue(!this.frozen, "Cannot add Channel because RabbitResourceHolder is frozen");
     AssertUtils.ArgumentNotNull(channel, "Channel must not be null");
     if (!this.channels.Contains(channel))
     {
         this.channels.Add(channel);
         if (connection != null)
         {
             List <IClientSession> channels = this.channelsPerConnection[connection];
             //TODO double check, what about TryGet..
             if (channels == null)
             {
                 channels = new List <IClientSession>();
                 this.channelsPerConnection.Add(connection, channels);
             }
             channels.Add(channel);
         }
     }
 }
Exemplo n.º 28
0
        public static long GenerateMessageId(this IClientSession session)
        {
            if (session.LastMessageId >= 4194303 - 4)
            {
                session.LastMessageId = 0;
            }
            else
            {
                session.LastMessageId += 4;
            }

            var seconds = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;

            var newMessageId =
                ((seconds / 1000 + session.TimeOffset) << 32) |
                ((seconds % 1000) << 22) |
                session.LastMessageId;

            return(newMessageId);
        }
Exemplo n.º 29
0
        public async Task DataAsItemList()
        {
            using (var connector = new Connector())
            {
                IClientSession clientSession = connector.Login("User1", "");

                IItem item1 = connector.Tree.GetOrAddItem("Node1\\Node2\\Node3.item1");
                Assert.AreEqual("Node1\\Node2\\Node3.item1", item1.Path);
                IItem item2 = connector.Tree.GetOrAddItem("Node2\\Node4.item2");
                IItem item3 = connector.Tree.GetOrAddItem("Node1\\Node3.item3");

                item1.DataAsItemList = new[] { item2, item3 };
                await item1.StoreAsync(clientSession);

                await item1.LoadAsync();

                Assert.AreEqual("Node2\\Node4.item2\nNode1\\Node3.item3", item1.DataAsString);
            }
            return;
        }
        public void MessageTransfer(IMessage m)
        {
            BinaryReader reader = new BinaryReader(m.Body, Encoding.UTF8);

            byte[] buffer = new byte[m.Body.Length - m.Body.Position];
            reader.Read(buffer, 0, buffer.Length);
            string str = new ASCIIEncoding().GetString(buffer);

            Console.WriteLine("Message: " + str);
            this._range.Add(m.Id);
            if (str.Equals("That's all, folks!"))
            {
                this._session.MessageAccept(this._range, new Option[0]);
                IClientSession session = this._session;
                lock (session)
                {
                    Monitor.Pulse(this._session);
                }
            }
        }
Exemplo n.º 31
0
        public void queueLifecycle()
        {
            _log.Debug("Running: queueLifecycle");
            IClientSession ssn = Client.CreateSession(0);

            ssn.QueueDeclare("queue1", null, null);
            ssn.Sync();
            ssn.QueueDelete("queue1");
            ssn.Sync();
            try
            {
                ssn.ExchangeBind("queue1", "amq.direct", "queue1", null);
                ssn.Sync();
            }
            catch (SessionException)
            {
                // as expected
            }
            // This test fails if an exception is thrown
        }
Exemplo n.º 32
0
        public void BeginConnect(EndPoint serverEndPoint)
        {
            if (PipeLineProcessor == null)
            {
                throw new Exception("This client has not been initialized.");
            }

            m_Session               = new AsyncTcpSession(serverEndPoint, 4096);
            m_Session.Connected    += new EventHandler(m_Session_Connected);
            m_Session.Error        += new EventHandler <ErrorEventArgs>(m_Session_Error);
            m_Session.Closed       += new EventHandler(m_Session_Closed);
            m_Session.DataReceived += new EventHandler <DataEventArgs>(m_Session_DataReceived);

            if (ReceiveBufferSize > 0)
            {
                m_Session.ReceiveBufferSize = ReceiveBufferSize;
            }

            m_Session.Connect();
        }
Exemplo n.º 33
0
        public bool rcvMeta(IClientSession session, IMutableMessage message)
        {
            if (Channel_Fields.META_HANDSHAKE.Equals(message.Channel))
            {
                Dictionary<String, Object> ext = (Dictionary<String, Object>)message.getExt(false);
                _serverSupportsAcks = ext != null && true.Equals(ext[EXT_FIELD]);
            }
            else if (_serverSupportsAcks && true.Equals(message[Message_Fields.SUCCESSFUL_FIELD]) && Channel_Fields.META_CONNECT.Equals(message.Channel))
            {
                Dictionary<String, Object> ext = (Dictionary<String, Object>)message.getExt(false);
                if (ext != null)
                {
                    Object ack;
                    ext.TryGetValue(EXT_FIELD, out ack);
                    _ackId = ObjectConverter.ToInt32(ack, _ackId);
                }
            }

            return true;
        }
Exemplo n.º 34
0
        private static void Main(string[] args)
        {
            string host        = ConfigurationManager.AppSettings["Host"];
            int    port        = int.Parse(ConfigurationManager.AppSettings["Port"]);
            string virtualhost = ConfigurationManager.AppSettings["VirtualHost"];
            string username    = ConfigurationManager.AppSettings["Username"];
            string password    = ConfigurationManager.AppSettings["Password"];

            Client connection = new Client();

            try
            {
                connection.Connect(host, port, virtualhost, username, password);
                IClientSession session = connection.CreateSession(50000);

                //--------- Main body of program --------------------------------------------
                // Create a queue named "message_queue", and route all messages whose
                // routing key is "routing_key" to this newly created queue.

                session.QueueDeclare("message_queue");
                session.ExchangeBind("message_queue", "amq.direct", "routing_key");

                lock (session)
                {
                    // Create a listener and subscribe it to the queue named "message_queue"
                    IMessageListener listener = new MessageListener(session);
                    session.AttachMessageListener(listener, "message_queue");
                    session.MessageSubscribe("message_queue");
                    // Receive messages until all messages are received
                    Monitor.Wait(session);
                }

                //---------------------------------------------------------------------------

                connection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: \n" + e.StackTrace);
            }
        }
Exemplo n.º 35
0
 public void ReConnect()
 {
     if (!isStopRequest)
     {
         ThreadPool.QueueUserWorkItem(o =>
         {
             if (!isStopRequest)
             {
                 Thread.Sleep(1000);
                 log.Info("ReConnect");
                 Connect(this.clientInfo);
                 if (IsConnected)
                 {
                     log.Info("ReSubscribe Topic");
                     _session = _conn.createSession();
                     _session.subscribe(topics, this);
                 }
             }
         });
     }
 }
Exemplo n.º 36
0
        private static void Main(string[] args)
        {
            string host        = ConfigurationManager.AppSettings["Host"];
            int    port        = int.Parse(ConfigurationManager.AppSettings["Port"]);
            string virtualhost = ConfigurationManager.AppSettings["VirtualHost"];
            string username    = ConfigurationManager.AppSettings["Username"];
            string password    = ConfigurationManager.AppSettings["Password"];

            Client connection = new Client();

            try
            {
                connection.Connect(host, port, virtualhost, username, password);
                IClientSession session = connection.CreateSession(50000);

                //--------- Main body of program --------------------------------------------

                lock (session)
                {
                    Console.WriteLine("Listening for messages ...");
                    // Create a listener
                    prepareQueue("usa", "usa.#", session);
                    prepareQueue("europe", "europe.#", session);
                    prepareQueue("news", "#.news", session);
                    prepareQueue("weather", "#.weather", session);
                    while (_count > 0)
                    {
                        Monitor.Wait(session);
                    }
                }

                //---------------------------------------------------------------------------

                connection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: \n" + e.StackTrace);
            }
        }
Exemplo n.º 37
0
        /// <summary>
        /// Callback method invoked every time a meta message is being sent.
        /// </summary>
        /// <returns>Always true.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="message"/> is null.</exception>
        public override bool SendMeta(IClientSession session, IMutableMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            long now = CurrentTimeMillis();
            IDictionary <string, object> timesync
                = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase)
                {
                { "tc", now },
                { "l", _lag },
                { "o", _offset }
                };

            IDictionary <string, object> ext = message.GetExtension(true);

            lock (ext) ext[ExtensionField] = timesync;

            return(true);
        }
Exemplo n.º 38
0
        // Token: 0x060008F6 RID: 2294 RVA: 0x0001E47C File Offset: 0x0001C67C
        private void OnSessionDataReceived(object sender, DataEventArgs e)
        {
            ProcessResult processResult;

            try
            {
                processResult = this.PipeLineProcessor.Process(new ArraySegment <byte>(e.Data, e.Offset, e.Length));
            }
            catch (Exception e2)
            {
                this.OnError(e2);
                this.m_Session.Close();
                return;
            }
            if (processResult.State == ProcessState.Error)
            {
                this.m_Session.Close();
                return;
            }
            if (processResult.State == ProcessState.Cached)
            {
                IClientSession session = this.m_Session;
                if (session != null)
                {
                    IBufferSetter bufferSetter = session as IBufferSetter;
                    if (bufferSetter != null)
                    {
                        bufferSetter.SetBuffer(new ArraySegment <byte>(new byte[session.ReceiveBufferSize]));
                    }
                }
            }
            if (processResult.Packages != null && processResult.Packages.Count > 0)
            {
                foreach (IPackageInfo package in processResult.Packages)
                {
                    this.HandlePackage(package);
                }
            }
        }
Exemplo n.º 39
0
 public IPipelineMessageItem[] GetMessages(IClientSession session, ref int lastMsgSeq, out bool valid)
 {
     lock (__lockObject)
     {
         valid = true;
         List <IPipelineMessageItem> buffer = null;
         if (!_messages.TryGetValue(session.SessionId, out buffer) ||
             buffer.Count == 0 ||
             buffer[0].Id == lastMsgSeq)
         {
             return(null);
         }
         else if (lastMsgSeq > 0 && buffer[buffer.Count - 1].Id > lastMsgSeq)
         {
             valid = false;
             return(null);
         }
         var lst = lastMsgSeq;
         lastMsgSeq = buffer[0].Id;
         return(buffer.TakeWhile(i => i.Id > lst).Reverse().ToArray());
     }
 }
Exemplo n.º 40
0
        public bool ReceiveMeta(IClientSession session, IMutableMessage message)
        {
            if (ChannelFields.MetaHandshake.Equals(message.Channel))
            {
                var ext = (Dictionary <string, object>)message.GetExt(false);
                _serverSupportsAcks = ext != null && true.Equals(ext[ExtField]);
            }
            else if (_serverSupportsAcks && true.Equals(message[MessageFields.SuccessfulField]) && ChannelFields.MetaConnect.Equals(message.Channel))
            {
                var ext = (Dictionary <string, object>)message.GetExt(false);

                if (ext == null)
                {
                    return(true);
                }

                ext.TryGetValue(ExtField, out var ack);
                _ackId = ObjectConverter.ToInt32(ack, _ackId);
            }

            return(true);
        }
 public bool send(IClientSession session, IMutableMessage message)
 {
     return true;
 }
Exemplo n.º 42
0
 public void CloseSession(IClientSession session)
 {
     this.DisposeSession(session as ClientSession);
 }
Exemplo n.º 43
0
 protected PerfTestClient(Options options)
 {
     _options = options;
     _connection = new Client();
     _connection.Connect(options.Broker, options.Port, "test", "guest", "guest");
     _session = _connection.CreateSession(50000);
 }
Exemplo n.º 44
0
 // Methods
 public MessageListener(IClientSession session)
 {
     this._session = session;
 }
Exemplo n.º 45
0
		protected void TryToConnect() {
			reqsOutstanding = 1 ;		
			Agent newAgent = new Agent(this,0,"BrokerAgent") ;
			Agents.Add(newAgent.AgentKey(), newAgent) ;
			client = new Client() ;
			client.Connect(url.Hostname, url.Port, null, url.AuthName, url.AuthPassword) ;
			clientSession = client.CreateSession(timeout) ;		
			//clientSession.SetAutoSync(false) ;
			string name = System.Text.Encoding.UTF8.GetString(clientSession.GetName()) ;
			replyName = "reply-" + name ;
			topicName = "topic-" + name ;
			clientSession.SetAutoSync(true) ;
			Option[] options = new Option[] {Option.EXCLUSIVE, Option.AUTO_DELETE} ;
		
			// This queue is used for responses to messages which are sent.	
			clientSession.QueueDeclare(replyName,options) ;
			clientSession.ExchangeBind(replyName,"amq.direct",replyName) ;
			clientSession.AttachMessageListener(this, "rdest") ;			
			clientSession.MessageSubscribe(replyName,"rdest",MessageAcceptMode.NONE,MessageAcquireMode.PRE_ACQUIRED,null,0,null) ;			  			  						
            clientSession.MessageSetFlowMode("rdest", MessageFlowMode.WINDOW);
            clientSession.MessageFlow("rdest", MessageCreditUnit.BYTE, ClientSession.MESSAGE_FLOW_MAX_BYTES);
            clientSession.MessageFlow("rdest", MessageCreditUnit.MESSAGE, ClientSession.MESSAGE_FLOW_MAX_BYTES);  			
		
			// This queue is used for unsolicited messages sent to this class.
			clientSession.QueueDeclare(topicName, options) ;
			clientSession.AttachMessageListener(this, "tdest") ;			
			clientSession.MessageSubscribe(topicName,"tdest",MessageAcceptMode.NONE,MessageAcquireMode.PRE_ACQUIRED,null,0,null) ;							  									
            clientSession.MessageSetFlowMode("tdest", MessageFlowMode.WINDOW);
            clientSession.MessageFlow("tdest", MessageCreditUnit.BYTE, ClientSession.MESSAGE_FLOW_MAX_BYTES);
            clientSession.MessageFlow("tdest", MessageCreditUnit.MESSAGE, ClientSession.MESSAGE_FLOW_MAX_BYTES);  				
			
			outSession = client.CreateSession(timeout) ;	
			outSession.ExchangeBind(replyName,"amq.direct",replyName) ;
			
			connected = true ;
			consoleSession.HandleBrokerConnect(this) ;		
				
			
			IEncoder encoder = CreateEncoder() ;
			this.SetHeader(encoder, 'B', 0) ;
			this.Send(encoder) ;
		}
Exemplo n.º 46
0
 public MyListener(IClientSession session, object wl)
 {
     _wl = wl;
     _session = session;
     _count = 0;
 }
Exemplo n.º 47
0
 public bool ContainsChannel(IClientSession channel)
 {
     return channels.Contains(channel);
 }
Exemplo n.º 48
0
 public QpidResourceHolder(IClientSession channel)
 {
     AddChannel(channel);
     this.frozen = true;
 }
Exemplo n.º 49
0
 public QpidResourceHolder(IClient connection, IClientSession channel)
 {
     AddConnection(connection);
     AddChannel(channel, connection);
     this.frozen = true;
 }
Exemplo n.º 50
0
 public ClientMessageListener(IClientSession session)
 {
     _session = session;
 }
Exemplo n.º 51
0
 public void AddChannel(IClientSession channel)
 {
     AddChannel(channel, null);
 }
Exemplo n.º 52
0
 internal void Singin(IClientSession client)
 {
     this.Status = ChatUserStatus.Online;
     if (_sessions.AddIfNotExists(client))
     {
         client.Closing += new EventHandler<EventArgs>(client_Closing);
         BroadcastStatus();
     }
 }
Exemplo n.º 53
0
 public static bool IsChannelTransactional(IClientSession session, IClientFactory clientFactory )
 {
     //TODO implement
     return false;
 }
Exemplo n.º 54
0
        /// <summary>
        /// Called when Excel requests the first RTD topic for the server. 
        /// Connect to the broker, returns a on success and 0 otherwise
        /// </summary>
        /// <param name="CallbackObject"></param>
        /// <returns></returns>
        public int ServerStart(IRTDUpdateEvent CallbackObject)
        {
            _onMessage = CallbackObject;  
            string host = "localhost";
            string port = "5673";
            string virtualhost = "test";
            string username = "******";
            string password = "******";
            _messageProcessor = getMessage;
          
            if( ConfigurationManager.AppSettings["Host"] != null )
            {
                host = ConfigurationManager.AppSettings["Host"];
            }
            if (ConfigurationManager.AppSettings["Port"] != null)
            {
                port = ConfigurationManager.AppSettings["Port"];
            }
            if (ConfigurationManager.AppSettings["VirtualHost"] != null)
            {
                virtualhost = ConfigurationManager.AppSettings["VirtualHost"];
            }
            if (ConfigurationManager.AppSettings["Username"] != null)
            {
                username = ConfigurationManager.AppSettings["UserName"];
            }
            if (ConfigurationManager.AppSettings["Password"] != null)
            {
                password = ConfigurationManager.AppSettings["Password"];
            }
            if (ConfigurationManager.AppSettings["ProcessorAssembly"] != null)
            {
                try
                {
                    Assembly a = Assembly.LoadFrom(ConfigurationManager.AppSettings["ProcessorAssembly"]);
                    Object o = a.CreateInstance(ConfigurationManager.AppSettings["ProcessorClass"]);
                    MessageProcessor p = (MessageProcessor) o;
                    _messageProcessor = p.ProcessMessage;
                }
                catch (Exception e)
                {
                    System.Windows.Forms.MessageBox.Show("Error: \n" + e.StackTrace);         
                    return 0;
                }
            }

            System.Windows.Forms.MessageBox.Show("Connection parameters: \n host: " + host + "\n port: " 
                                                 + port + "\n user: "******"Error: \n" + e.StackTrace);         
                return 0;
            }
            
            // always successful 
            return 1;
        }
        public void BeginConnect(EndPoint remoteEndPoint)
        {
            if (PipeLineProcessor == null)
                throw new Exception("This client has not been initialized.");

            var session = GetUnderlyingSession();

            var localEndPoint = m_EndPointToBind;

            if (localEndPoint != null)
            {
                session.LocalEndPoint = localEndPoint;
            }

            session.NoDelay = NoDelay;

            if (Proxy != null)
                session.Proxy = Proxy;

            session.Connected += new EventHandler(OnSessionConnected);
            session.Error += new EventHandler<ErrorEventArgs>(OnSessionError);
            session.Closed += new EventHandler(OnSessionClosed);
            session.DataReceived += new EventHandler<DataEventArgs>(OnSessionDataReceived);

            if (ReceiveBufferSize > 0)
                session.ReceiveBufferSize = ReceiveBufferSize;

            m_Session = session;
            session.Connect(remoteEndPoint);
        }
        private TaskCompletionSource<bool> InitConnect(EndPoint remoteEndPoint)
        {
            var session = GetUnderlyingSession();

#if !SILVERLIGHT
            var localEndPoint = m_EndPointToBind;

            if (localEndPoint != null)
            {
                session.LocalEndPoint = m_EndPointToBind;
            }
#endif

#if !__IOS__
            session.NoDelay = NoDelay;
#endif
            if (Proxy != null)
                session.Proxy = Proxy;
                
            session.Connected += new EventHandler(OnSessionConnected);
            session.Error += new EventHandler<ErrorEventArgs>(OnSessionError);
            session.Closed += new EventHandler(OnSessionClosed);
            session.DataReceived += new EventHandler<DataEventArgs>(OnSessionDataReceived);

            if (ReceiveBufferSize > 0)
                session.ReceiveBufferSize = ReceiveBufferSize;

            m_Session = session;
            
            var taskSrc = m_ConnectTaskSource = new TaskCompletionSource<bool>();

            session.Connect(remoteEndPoint);
            
            return taskSrc;
        }
Exemplo n.º 57
0
            public void onMessage(IClientSession session, String channel, Cometd.Bayeux.IMessage message)
            {
                if (message.Successful)
                {
                    Console.WriteLine("had something on " + message.Channel);
                    Console.WriteLine("namely " + message.JSON);
                }

                if (channel.Equals("/do/select")) //|| (message is AlexRangeRequest)
                {

                }

                if (channel.Equals("/get/data"))
                {
                    //call Alex_API from here
                }
            }
Exemplo n.º 58
0
 private void SetSessionByUser(string login, IClientSession session, bool setting)
 {
     List<IClientSession> buffer = null;
     if (!_sessionsByUser.TryGetValue(login, out buffer))
         buffer = _sessionsByUser[login] = new List<IClientSession>();
     if (setting)
         buffer.Add(session);
     else
         buffer.Remove(session);
 }
Exemplo n.º 59
0
 public SyncListener(IClientSession session, CircularBuffer<IMessage> buffer)
 {
     _buffer = buffer;
     _session = session;
 }
Exemplo n.º 60
0
 public void AddChannel(IClientSession channel, IClient connection)
 {
     AssertUtils.IsTrue(!this.frozen, "Cannot add Channel because RabbitResourceHolder is frozen");
     AssertUtils.ArgumentNotNull(channel, "Channel must not be null");
     if (!this.channels.Contains(channel))
     {
         this.channels.Add(channel);
         if (connection != null)
         {
             List<IClientSession> channels = this.channelsPerConnection[connection];
             //TODO double check, what about TryGet..
             if (channels == null)
             {
                 channels = new List<IClientSession>();
                 this.channelsPerConnection.Add(connection, channels);
             }
             channels.Add(channel);
         }
     }
 }