示例#1
0
            public HttpPostServer(int port) : base(port)
            {
                Hostname = "+";

                Get["/"] = _ => $"RIS - TETRAControl Webserver running on Port {port}";

                Post["/"] = arg =>
                {
                    string documentContents;
                    using (var receiveStream = arg.InputStream)
                    {
                        using (var readStream = new StreamReader(receiveStream, Encoding.UTF8))
                        {
                            documentContents = readStream.ReadToEnd();
                        }
                    }

                    var response = new RestResponse
                    {
                        Content = documentContents
                    };
                    MessageReceived.Invoke(this, response);

                    return("OK");
                };
            }
示例#2
0
 protected void OnMessageReceived(Message message)
 {
     if (MessageReceived != null)
     {
         MessageReceived.Invoke(this, message);
     }
 }
示例#3
0
文件: MIO.cs 项目: AscheLeee/KenBot
        public string AttemptRead()
        {
            Stopwatch TimeoutTimer = new Stopwatch();

            TimeoutTimer.Start();
            while (TimeoutTimer.Elapsed.Seconds <= ReadTimeoutDuration.Seconds)
            {
                if (Stream.DataAvailable)
                {
                    Buffer = new byte[512];
                    int numOfBytes = Stream.Read(Buffer, 0, Buffer.Length);
                    Response = Encoding.ASCII.GetString(Buffer, 0, numOfBytes);
                    string Content = Response;
                    MessageReceived.Invoke(Content);
                    TimeoutTimer.Stop();
                    return(Response);
                }
                else
                {
                    Response = "No data available in NetworkStream to read.";
                }
            }
            TimeoutTimer.Stop();
            return(Response);
        }
示例#4
0
        private async void HandleMessagesFromPlayer(Guid playerGuid)
        {
            var playerHandle = _playerHandles[playerGuid];

            while (true)
            {
                lock (playerHandle.Lock)
                {
                    if (playerHandle.Queue.IsEmpty)
                    {
                        playerHandle.IsProcessed = false;
                        break;
                    }

                    playerHandle.IsProcessed = true;
                }

                IRequestMessage requestMessage;
                while (!playerHandle.Queue.TryDequeue(out requestMessage))
                {
                    await Task.Delay(10);
                }

                var timeSpan = Convert.ToInt32(_actionCosts.GetDelayFor(requestMessage.GetActionInfo()));
                await Task.Delay(timeSpan);

                MessageReceived.Invoke(this, requestMessage);
            }
        }
        private async void PublishActivities(ActivitySet set)
        {
            //Debug.Log($"[BOT] Received activity set [{set.Activities.Count}]");
            foreach (var activity in set.Activities)
            {
                if (activity.Type == "message")
                {
                    if (OnlyBotMessages && activity.From?.Id == Account.Id)
                    {
                        continue;
                    }

                    UnityMainThreadDispatcher.Instance().Enqueue(() => MessageReceived.Invoke(activity));

                    float messageDelta = (float)DateTime.Now.Subtract(m_LastTime).TotalSeconds;
                    m_LastTime = DateTime.Now;
                    if (messageDelta < messageDelay)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(messageDelay - messageDelta));
                    }
                }
                else
                {
                    UnityMainThreadDispatcher.Instance().Enqueue(() => SystemActivityReceived.Invoke(activity));
                }
            }
        }
示例#6
0
 private void RaiseMessageRecived(byte[] buffer)
 {
     if (MessageReceived != null)
     {
         MessageReceived.Invoke(_workSocket, buffer);
     }
 }
示例#7
0
 private void Connection_OnMessage(string msg)
 {
     if (!string.IsNullOrEmpty(msg))
     {
         MessageReceived.Invoke(this, new MessageWebSocketMessageReceivedEventArgs(msg));
     }
 }
示例#8
0
 private void ReceiverThread()
 {
     while (running)
     {
         try
         {
             var data    = port.GetCommand();
             var message = serializer.Deserialize(data);
             if (logger.IsEnabled(LogLevel.Debug))
             {
                 logger.LogDebug("IN < {0}", MessageToString(message));
             }
             MessageReceived.Invoke(this, message);
         }
         catch (MidiSerializerException e)
         {
             logger.LogWarning(e, e.Message);
         }
         catch (TeVirtualMidiException e)
         {
             if (running && e.ReasonCode != (int)TeVirtualMidiException.Code.InvalidHandle)
             {
                 logger.LogError(e, e.Message);
             }
         }
         catch (Exception e)
         {
             logger.LogError(e, e.Message);
         }
     }
 }
 private void OnMessageReceived(object sender, DatagramReceivedEventArgs e)
 {
     if (MessageReceived != null)
     {
         MessageReceived.Invoke(sender, e);
     }
 }
示例#10
0
        /// <summary>
        ///     Invoked when DarkRift receives a message from the server.
        /// </summary>
        /// <param name="sender">THe client that received the message.</param>
        /// <param name="e">The arguments for the event.</param>
        void Client_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            //If we're handling multithreading then pass the event to the dispatcher
            if (invokeFromDispatcher)
            {
                Dispatcher.InvokeAsync(
                    () =>
                {
                    if (sniffData)
                    {
                        Debug.Log("Message Received");              //TODO more information!
                    }
                    MessageReceived.Invoke(sender, e);
                }
                    );
            }
            else
            {
                if (sniffData)
                {
                    Dispatcher.InvokeAsync(
                        () => Debug.Log("Message Received")      //TODO more information!
                        );
                }

                MessageReceived.Invoke(sender, e);
            }
        }
示例#11
0
        void InputDevice_MessageReceived(object sender, MidiMessage message, int channel, int key, int value)
        {
            ControlMap map = null;

            map = FindMap(channel, key);


            if (MessageReceived != null)
            {
                MessageReceived.Invoke(this, message, channel, key, value);
            }

            if (map == null)
            {
                if (UnhandledMessageReceived != null)
                {
                    UnhandledMessageReceived.Invoke(this, message, channel, key, value);
                }
            }
            else
            {
                map.DispatchMessage(message, channel, key, value);
                if (map.AutoRepeat && map.KeyDown && !AutoRepeatList.Contains(map))
                {
                    AutoRepeatList.Add(map);
                }
                else if (map.AutoRepeat && !map.KeyDown && AutoRepeatList.Contains(map))
                {
                    AutoRepeatList.Remove(map);
                }
            }
        }
示例#12
0
    void OnReceive(IAsyncResult ar)
    {
        var s     = (UdpState)ar.AsyncState;
        var bytes = s.client.EndReceive(ar, ref s.dataStream);
        var msg   = Serializer.Deserialize <Message>(bytes);

        switch (msg.type)
        {
        case MessageType.None:
            break;

        case MessageType.LogIn:
            MessageReceived.Invoke(msg, s);
            break;

        case MessageType.LogOut:
            MessageReceived.Invoke(msg, s);
            break;

        case MessageType.Movement:
            MessageReceived.Invoke(msg, s);
            break;

        case MessageType.Tick:
            MessageReceived.Invoke(msg, s);
            break;
        }
        client.Receive(OnReceive);
    }
示例#13
0
 private async Task DiscordShardedClientOnMessageReceived(SocketMessage arg)
 {
     if (MessageReceived != null)
     {
         await MessageReceived.Invoke(this, arg).ConfigureAwait(false);
     }
 }
 private void OnMessageReceieved(object sender, MqttApplicationMessageReceivedEventArgs args)
 {
     if (MessageReceived != null)
     {
         _dispatcher.Post(() => MessageReceived.Invoke(_id, sender, args));
     }
 }
示例#15
0
        private void ProcessRequest(string body)
        {
            var e = JsonConvert.DeserializeObject <Event>(body);

            foreach (var entry in e.Entries)
            {
                foreach (var item in entry.Items)
                {
                    if (item.Message != null && MessageReceived != null)
                    {
                        MessageEventArgs messageEventArgs = new MessageEventArgs()
                        {
                            Sender  = item.Sender.Id,
                            Message = item.Message
                        };

                        ThreadPool.QueueUserWorkItem(state => MessageReceived.Invoke(messageEventArgs));
                    }

                    if (item.Postback != null && PostbackReceived != null)
                    {
                        PostbackEventArgs postbackEventArgs = new PostbackEventArgs()
                        {
                            Sender   = item.Sender.Id,
                            Postback = item.Postback
                        };

                        ThreadPool.QueueUserWorkItem(state => PostbackReceived.Invoke(postbackEventArgs));
                    }
                }
            }
        }
示例#16
0
 public virtual void OnMessageReceived(NetCoreEventArgs e)
 {
     if (MessageReceived == null)
     {
         throw new Exception("No registered handler for MessageReceived!");
     }
     MessageReceived.Invoke(this, e);
 }
示例#17
0
 private void GotMessage(uint status, uint senderId, uint groupId, uint messageId, byte[] data, object context)
 {
     if (MessageReceived != null)
     {
         var args = new LiveConnectMessageArgs(senderId, messageId, data);
         MessageReceived.Invoke(this, args);
     }
 }
示例#18
0
 public Form1()
 {
     InitializeComponent();
     this.TopMost          = true;
     this.btnClose.Enabled = false;
     MessageReceived      += Form1_MessageReceived;
     MessageReceived.Invoke();
 }
示例#19
0
 // Update is called once per frame
 void Update()
 {
     if (PacketsAvailable() > 0)
     {
         ArduinoBuffer packet = GetReceivedPacket();
         OnMessageReceived.Invoke(packet);
     }
 }
 /// <summary>
 /// This method processes the message and triggers the MessageReceived event.
 /// </summary>
 /// <param name="dataGram"></param>
 private void OnMessageReceived(DataGram dataGram)
 {
     if (MessageReceived != null)
     {
         // trigger this async
         MessageReceived.Invoke(this, new XDMessageEventArgs(dataGram));
     }
 }
示例#21
0
 private void OnMessageReceived(string message, Color color)
 {
     if (MessageReceived == null)
     {
         return;
     }
     MessageReceived.Invoke(message, color);
 }
示例#22
0
 public override void ReceiveMessage(string rosMessage)
 {
     if (MessageReceived != null)
     {
         MessageContainer parsedMessage = JsonUtility.FromJson <MessageContainer> (rosMessage);
         MessageReceived.Invoke(parsedMessage.msg);
     }
 }
示例#23
0
        public void LoadEvents()
        {
            Client.UserJoined += async(u) =>
            {
                Task.Run(() => UserJoin?.Invoke(new RuntimeUser(u)));
            };

            Client.UserLeft += async(u) =>
            {
                Task.Run(() => UserLeft?.Invoke(new RuntimeUser(u)));
            };

            Client.UserUpdated += async(u, unew) =>
            {
                RuntimeUser userOld = new RuntimeUser(u);
                RuntimeUser userNew = new RuntimeUser(unew);
                Task.Run(() => UserUpdated?.Invoke(userOld, userNew));
            };

            Client.MessageReceived += async(m) =>
            {
                RuntimeMessage newMessage = new RuntimeMessage(m);
                if (MessageReceived != null)
                {
                    await MessageReceived.Invoke(newMessage);
                }
            };

            Client.JoinedGuild += async(g) =>
            {
                Task.Run(async() =>
                {
                    RuntimeGuild guild = new RuntimeGuild(g);
                    await GuildJoin?.Invoke(guild);
                });
            };

            Client.LeftGuild += async(g) =>
            {
                RuntimeGuild guild = new RuntimeGuild(g);
                await GuildLeave?.Invoke(guild);
            };

            foreach (var shard in Client.Shards)
            {
                shard.Disconnected += async(ex) =>
                {
                    await OnShardDisconnect?.Invoke(ex, shard.ShardId);
                };
                shard.Connected += async() =>
                {
                    if (OnShardConnect != null)
                    {
                        await OnShardConnect.Invoke(shard.ShardId);
                    }
                };
            }
        }
示例#24
0
        private void OnWebSocketMessage(ResponseMessage resp)
        {
            var msg = JsonConvert.DeserializeObject <PushbulletMessage>(resp.Text);

            if (msg.MessageType == "push" && msg.Push.PushType == "mirror")
            {
                MessageReceived.Invoke(this, msg.Push);
            }
        }
示例#25
0
        private async Task OnChannelMessaged(object source, ServerMessagedEventArgs args)
        {
            if (MessageReceived == null)
            {
                return;
            }

            await MessageReceived.Invoke(source, args);
        }
        private void HandleChatMessage(IIncommingMessage message)
        {
            var packet = message.Deserialize(new ChatMessagePacket());

            if (MessageReceived != null)
            {
                MessageReceived.Invoke(packet);
            }
        }
示例#27
0
        /// <summary>
        /// Logs the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="type">The type.</param>
        public void Log(string message, MessageTypeEnum type)
        {
            MessageReceivedEventArgs msg = new MessageReceivedEventArgs(message, type);

            MessageReceived.Invoke(this, msg);
            this.logs.Add(msg);
            string[] args = { message, type.ToString() };
            //NewLogEntry?.Invoke(this, new CommandReceivedEventArgs((int) CommandEnum.LogCommand, args, null));
        }
示例#28
0
 public bool TryRaise(SnooperMessage Message, SnooperSocketClient Client)
 {
     if (MessageReceived == null)
     {
         return(false);
     }
     MessageReceived.Invoke(Message, Client);
     return(true);
 }
        public async Task <bool> TryRaise(SnooperMessage Message)
        {
            if (MessageReceived == null)
            {
                return(false);
            }
            await MessageReceived.Invoke(Message);

            return(true);
        }
示例#30
0
        protected void RaiseMessageReceived(Message message)
        {
            if (MessageReceived == null)
            {
                return;
            }
            var thread = new Thread(e => MessageReceived.Invoke(this, message));

            thread.Start();
        }
示例#31
0
		/// <summary>
		/// Retrieves a set of mail messages by their unique identifier message attributes
		/// providing fine-grained control over which message parts to retrieve of each
		/// respective message.
		/// </summary>
		/// <param name="uids">An array of unique identifiers of the mail messages to
		/// retrieve</param>
		/// <param name="callback">A delegate which will be invoked for every MIME body
		/// part of a mail message to determine whether it should be fetched from the
		/// server or skipped.</param>
		/// <param name="seen">Set this to true to set the \Seen flag for the fetched
		/// messages on the server.</param>
		/// <param name="mailbox">The mailbox the messages will be retrieved from. If this
		/// parameter is omitted, the value of the DefaultMailbox property is used to
		/// determine the mailbox to operate on.</param>
		/// <exception cref="NotAuthenticatedException">Thrown if the method was called
		/// in a non-authenticated state, i.e. before logging into the server with
		/// valid credentials.</exception>
		/// <exception cref="BadServerResponseException">Thrown if the mail messages could
		/// not be fetched. The message property of the exception contains the error message
		/// returned by the server.</exception>
		/// <returns>An array of initialized instances of the MailMessage class representing
		/// the fetched mail messages</returns>
		/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each
		/// message which uniquely identifies the message within a mailbox. No two
		/// messages in a mailbox share the the same UID.</remarks>
		/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="GetMessages-3"]/*'/>
		public List<MessageInfo> GetMessages(long[] uids, ExaminePartDelegate callback,
			bool seen = true, MessageReceived messageReceived = null) {
                if (!Authed)
                    throw new NotAuthenticatedException();
                lock (sequenceLock)
                {
                    if (this.selectedMailbox == null)
                        throw new InvalidOperationException("No mailbox or folder currently selected.");

                    List<MessageInfo> infos = GetMailHeader(uids, seen);

                    Dictionary<long,string> structures = GetBodystructure(uids);
                    try
                    {
                        foreach (MessageInfo info in infos)
                        {
                            Bodypart[] parts = Bodystructure.Parse(structures[info.UID]);
                            foreach (Bodypart part in parts)
                            {
                                /* Let delegate decide if part should be fetched or not */
                                if (callback(part) == true)
                                {
                                    string content = GetBodypart(info.UID, part.PartNumber, seen);
                                    info.Envelope.AddBodypart(part, content);
                                }
                            }

                            if (messageReceived != null)
                                messageReceived.Invoke(info);
                        }
                    }
                    catch (FormatException)
                    {
                        throw new BadServerResponseException("Server returned erroneous " +
                            "body structure.");
                    }
                   
                    return infos;
                }
		}
示例#32
0
		/// <summary>
		/// Retrieves a set of mail messages by their unique identifier message attributes
		/// with the specified fetch option.
		/// </summary>
		/// <param name="uids">An array of unique identifiers of the mail messages to
		/// retrieve</param>
		/// <param name="options">A value from the FetchOptions enumeration which allows
		/// for fetching selective parts of a mail message.</param>
		/// <param name="seen">Set this to true to set the \Seen flag for the fetched
		/// messages on the server.</param>
		/// <param name="mailbox">The mailbox the messages will be retrieved from. If this
		/// parameter is omitted, the value of the DefaultMailbox property is used to
		/// determine the mailbox to operate on.</param>
		/// <exception cref="NotAuthenticatedException">Thrown if the method was called
		/// in a non-authenticated state, i.e. before logging into the server with
		/// valid credentials.</exception>
		/// <exception cref="BadServerResponseException">Thrown if the mail messages could
		/// not be fetched. The message property of the exception contains the error message
		/// returned by the server.</exception>
		/// <returns>An array of initialized instances of the MailMessage class representing
		/// the fetched mail messages</returns>
		/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each
		/// message which uniquely identifies the message within a mailbox. No two
		/// messages in a mailbox share the the same UID.</remarks>
		/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="GetMessages-2"]/*'/>
		public List<MessageInfo> GetMessages(long[] uids, FetchOptions options,
			bool seen = true, MessageReceived callback = null) {
            if (!Authed)
                throw new NotAuthenticatedException();
            lock (sequenceLock)
            {
                if (this.selectedMailbox == null)
                    throw new InvalidOperationException("No mailbox or folder currently selected.");

                List<MessageInfo> infos = GetMailHeader(uids, seen);

                if (options == FetchOptions.HeadersOnly)
                {
                    return infos;
                }
                /* Retrieve and parse the body structure of the mail message */
                Dictionary<long,string> structures = GetBodystructure(uids);
                try
                {
                    foreach (MessageInfo info in infos)
                    {
                        Bodypart[] parts = Bodystructure.Parse(structures[info.UID]);
                            
                        foreach (Bodypart part in parts)
                        {
                            if (options != FetchOptions.Normal &&
                                part.Disposition.Type == ContentDispositionType.Attachment)
                                continue;
                            if (options == FetchOptions.TextOnly && part.Type != ContentType.Text)
                                continue;
                            /* fetch the content */
                            string content = GetBodypart(info.UID, part.PartNumber, seen);

                            info.Envelope.AddBodypart(part, content);
                        }

                        if (callback != null)
                            callback.Invoke(info);
                    }
                }
                catch (FormatException)
                {
                    throw new BadServerResponseException("Server returned erroneous " +
                        "body structure.");
                }
           
                return infos;
            }
		}
示例#33
0
        private List<MessageInfo> GetMailHeader(long[] uids, bool seen = true, MessageReceived callback = null)
        {
            if (!Authed)
                throw new NotAuthenticatedException();
            lock (sequenceLock)
            {
                if (this.selectedMailbox == null)
                    throw new InvalidOperationException("No mailbox or folder currently selected.");

                string EXTRAHEADERS = "";

                if(this.supportsXGMEXT)
                    EXTRAHEADERS = "X-GM-LABELS X-GM-THRID X-GM-MSGID ";

                Dictionary<long,MessageInfo> headers = new Dictionary<long,MessageInfo>();
                Dictionary<long, string> rawResponse = new Dictionary<long, string>();
                string uidRange = Util.BuildUIDRange(uids);
                string tag = GetTag();
                string response = SendCommandGetResponse(tag + "UID FETCH " + uidRange + " (FLAGS " + EXTRAHEADERS + "BODY" +
                    (seen ? null : ".PEEK") + "[HEADER])");
                while (response.StartsWith("*"))
                {
                    MessageInfo info = new MessageInfo();
                    Match m = ImapParsing.Fetch.Match(response);
                    string builder = "";
                    if (m.Success)
                    {
                        int size = Convert.ToInt32(m.Groups[2].Value);
                        builder = GetData(size);
                        info.MessageNumber = Convert.ToInt64(m.Groups[1].Value);
                    }
                    m = ImapParsing.FetchUID.Match(response);
                    if (m.Success)
                        info.UID = Convert.ToInt64(m.Groups[1].Value);

                    info.RawHeader = builder;

                    headers.Add(info.UID, info);
                    rawResponse.Add(info.UID, response);

                    response = GetResponse();

                    //We need to go ahead and swallow this response
                    //Since we have already gathered the data from the stream
                    if (response == ")")
                        response = GetResponse();
                }

                if (!IsResponseOK(response, tag))
                    throw new BadServerResponseException(response);

                foreach (long uid in headers.Keys)
                {
                    MessageInfo info = headers[uid];
                    Match m = null;
                    response = rawResponse[uid];

                    if (this.supportsXGMEXT)
                    {
                        m = ImapParsing.FetchLabels.Match(response);
                        if (m.Success)
                        {
                            List<string> labels = Util.ParseLabels(Regex.Replace(m.Groups[1].Value, "(?!\\\\\")(\\\\)", string.Empty));

                            info.Labels = new List<string>();

                            foreach (string label in labels)
                            {
                                info.Labels.Add(Regex.Replace(label, "\"", string.Empty));
                            }
                        }

                        m = ImapParsing.FetchThreadID.Match(response);
                        if (m.Success)
                            info.ThreadID = m.Groups[1].Value;

                        m = ImapParsing.FetchMessageID.Match(response);
                        if (m.Success)
                            info.MessageID = m.Groups[1].Value;
                    }

                    m = ImapParsing.FetchFlags.Match(response);
                    if (m.Success)
                    {
                        info.Flags = m.Groups[1].Value.Split(' ').ToList();
                    }

                    info.Envelope = MessageBuilder.FromHeader(info.RawHeader);
                    info.Date = Util.ParseDateTime(info.Envelope.Headers["Date"]);

                    if (callback != null)
                        callback.Invoke(info);
                }

                return headers.Values.ToList();
            }
        }