Beispiel #1
0
        public void SendChatToTeam(ServerPlayer from, TeamColors to, string chat, bool action)
        {
            if (chat == string.Empty)
            {
                return;
            }

            ChatMessageEventArgs args = new ChatMessageEventArgs();

            args.From        = from;
            args.To          = null;
            args.ToTeam      = to;
            args.MessageText = chat;

            args.Action   = action;
            args.ChatType = from == null ? ChatMessageEventArgs.ChatMessageTypes.ServerTeamMessage : ChatMessageEventArgs.ChatMessageTypes.TeamMessage;

            if (args.ToTeam == TeamColors.NoTeam)
            {
                return;
            }

            MsgMessage msg = new MsgMessage();

            msg.MessageText = chat;
            msg.From        = from == null ? PlayerConstants.ServerPlayerID : from.PlayerID;
            msg.To          = PlayerConstants.GetTeamPlayerID(to);

            msg.MessageType = action ? MsgMessage.MessageTypes.ActionMessage : MsgMessage.MessageTypes.ChatMessage;

            Players.SendToTeam(msg, to, false);

            MessageSent?.Invoke(this, args);
        }
Beispiel #2
0
        public void SendChatToGroup(ServerPlayer from, GroupInfo to, string chat, bool action)
        {
            if (chat == string.Empty)
            {
                return;
            }

            ChatMessageEventArgs args = new ChatMessageEventArgs();

            args.From        = from;
            args.To          = null;
            args.ToTeam      = TeamColors.NoTeam;
            args.ToGroup     = to;
            args.MessageText = chat;

            args.Action   = action;
            args.ChatType = from == null ? ChatMessageEventArgs.ChatMessageTypes.ServerGroupMessage : ChatMessageEventArgs.ChatMessageTypes.GroupMessage;

            if (args.ToTeam == TeamColors.NoTeam)
            {
                return;
            }

            MsgMessage msg = new MsgMessage();

            msg.MessageText = chat;
            msg.From        = from == null ? PlayerConstants.ServerPlayerID : from.PlayerID;
            msg.To          = to.BroadcastID;

            msg.MessageType = action ? MsgMessage.MessageTypes.ActionMessage : MsgMessage.MessageTypes.ChatMessage;

            to.SentTo(msg, false);

            MessageSent?.Invoke(this, args);
        }
Beispiel #3
0
        public void SendChatToAll(ServerPlayer from, string chat, bool action)
        {
            if (chat == string.Empty)
            {
                return;
            }

            ChatMessageEventArgs args = new ChatMessageEventArgs();

            args.From        = from;
            args.To          = null;
            args.MessageText = chat;

            args.Action   = action;
            args.ChatType = from == null ? ChatMessageEventArgs.ChatMessageTypes.ServerAnnouncemnt : ChatMessageEventArgs.ChatMessageTypes.PublicMessage;

            MsgMessage msg = new MsgMessage();

            msg.MessageText = chat;
            msg.From        = from == null ? PlayerConstants.ServerPlayerID : from.PlayerID;
            msg.To          = PlayerConstants.AllPlayersID;

            msg.MessageType = action ? MsgMessage.MessageTypes.ActionMessage : MsgMessage.MessageTypes.ChatMessage;

            Players.SendToAll(msg, false);

            MessageSent?.Invoke(this, args);
        }
Beispiel #4
0
        public void TellMessage(string user, string message)
        {
            if (!IsAuthenticated)
            {
                throw new InvalidOperationException("Not authenticated. Request/set token first.");
            }

            if (AccountData == null)
            {
                throw new InvalidOperationException("No account data requested. Request account data first.");
            }

            try
            {
                var jObject = new JObject();
                jObject["chat_token"] = Token;
                jObject["username"]   = SelectedUser;
                jObject["tell"]       = user;
                jObject["msg"]        = message;

                Requester.PostRequest(Methods.MessageOutlet, jObject);
                MessageSent?.Invoke(this, new MessageEventArgs(new Message(string.Empty, Utilities.GetTime(), user, SelectedUser, string.Empty, message)));
            }
            catch (RequestException e)
            {
                ErrorOccured?.Invoke(this, new ErrorEventArgs(e));
            }
        }
Beispiel #5
0
 private void OnMessageSent(string message, bool error = false, string reason = "")
 {
     MessageSent?.Invoke(this, new NpMessageEventArgs()
     {
         Message = message, Error = error, Reason = reason
     });
 }
Beispiel #6
0
        /// <summary>
        /// Sends the specified string to the server.
        /// </summary>
        /// <remarks>
        /// Do not use this method directly except for stream initialization and closing.
        /// </remarks>
        /// <param name="xml">The string to send.</param>
        /// <exception cref="ArgumentNullException">The xml parameter is null.</exception>
        /// <exception cref="IOException">There was a failure while writing to the network.</exception>
        private void Send(string xml)
        {
            if (xml == null)
            {
                throw new ArgumentNullException("xml");
            }

            // XMPP is guaranteed to be UTF-8.
            byte[] buf = Encoding.UTF8.GetBytes(xml);
            lock (_writeLock)
            {
                try
                {
                    _stream.Write(buf, 0, buf.Length);
                    _messageId++;
                    MessageSent?.Invoke(this, new MessageSentEventArgs(xml));
                }
                catch
                {
                    Authenticated = false;
                    Connected     = false;

                    throw;
                }
            }
        }
Beispiel #7
0
 /// <summary>
 /// 发送信息线程方法
 /// </summary>
 private void SendThreadFunc()
 {
     Trace.WriteLine("Open send data tunnel");
     lock (this.asyncTcpClient)
     {
         while (this.asyncTcpClient.Connected)
         {
             if (msgs2send.Count > 0)
             {
                 try
                 {
                     var data = msgs2send.Dequeue();
                     if (data != null)
                     {
                         this.asyncTcpClient.Send(data);
                         MessageSent?.Invoke(this, new Message(this.Encoding.GetString(data)));
                     }
                 }
                 catch (Exception ex)
                 {
                     Trace.WriteLine(ex);
                 }
             }
             else
             {
                 Thread.Sleep(200);
             }
         }
     }
 }
        public async Task MulticastAsync(IdentityHash destinationId, byte[] payload)
        {
            byte[] symmetricKey;
            if (!identity.IdentityManager.TryLookupMulticastKey(destinationId, out symmetricKey))
            {
                throw new InvalidStateException("Attempted to multicast to destination of unknown key!");
            }

            var messageDto           = identity.EncodePacket(payload, symmetricKey);
            var localInsertionResult = await localMerkleTree.TryInsertAsync(messageDto).ConfigureAwait(false);

            if (localInsertionResult.Item1)
            {
                // "Decrypt the message"
                MessageSent?.Invoke(new MessageReceivedEventArgs(
                                        null,
                                        new BroadcastMessage {
                    SourceId         = IdentityHash.GetFlyweight(identity.PublicIdentityHash),
                    DestinationId    = destinationId,
                    DecryptedPayload = payload,
                    Dto = messageDto
                }
                                        ));
            }
        }
Beispiel #9
0
        /// <summary>
        /// Sends the specified string to the server.
        /// </summary>
        /// <remarks>
        /// Do not use this method directly except for stream initialization and closing.
        /// </remarks>
        /// <param name="message">The string to send.</param>
        /// <exception cref="ArgumentNullException">The xml parameter is null.</exception>
        /// <exception cref="IOException">There was a failure while writing to the network.</exception>
        private void Send(string message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            // Attach carriage return character if not present
            if (!message.EndsWith("\r"))
            {
                message += "\r";
            }

            byte[] buf = Encoding.ASCII.GetBytes(message);
            lock (_writeLock)
            {
                try
                {
                    _stream.Write(buf, 0, buf.Length);
                    MessageSent?.Invoke(this, new MessageSentEventArgs(message));
                }
                catch
                {
                    Close();
                    throw;
                }
            }
        }
        /// <summary>
        ///     Sends given message to host asynchronously using TcpClient with given cancellation token.
        /// </summary>
        /// <remarks>
        ///     Sunricher device does not accept messages with interval less than ~100ms, so this method will not run in parallel.
        ///     Internally uses queue to send one message at time.
        /// </remarks>
        /// <exception cref="OperationCanceledException">Operation was cancelled during connection to device.</exception>
        public async Task SendMessageAsync(Byte[] message, CancellationToken cancellationToken)
        {
            void SendMessageAction()
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return;                     //Return if already cancelled
                }
                var eventArgs = new LedMessageEventArgs(message);

                SendingMessage?.Invoke(this, eventArgs);

                if (_tcpClient == null)
                {
                    _tcpClient = new TcpClient();
                    _tcpClient.ConnectAsync(_host, _port).Wait(cancellationToken);                     //Will throw if cancelled during connection
                }

                var writeTask = _tcpClient
                                .GetStream()
                                .WriteAsync(message, 0, message.Length, cancellationToken);

                // ReSharper disable MethodSupportsCancellation
                writeTask.Wait();
                MessageSent?.Invoke(this, eventArgs);

                if (writeTask.Status == TaskStatus.RanToCompletion)
                {
                    Task.Delay(DelayAfterMessage).Wait();
                }
                // ReSharper restore MethodSupportsCancellation
            }

            await _serialQueue.Enqueue(SendMessageAction);
        }
Beispiel #11
0
        public void SendChatToUser(ServerPlayer from, ServerPlayer to, string chat, bool action)
        {
            if (chat == string.Empty)
            {
                return;
            }

            ChatMessageEventArgs args = new ChatMessageEventArgs();

            args.From        = from;
            args.To          = to;
            args.ToTeam      = to.ActualTeam;
            args.MessageText = chat;

            args.Action   = action;
            args.ChatType = from == null ? ChatMessageEventArgs.ChatMessageTypes.ServerPrivateMessage : ChatMessageEventArgs.ChatMessageTypes.PrivateMessage;

            if (args.To == null)
            {
                return;
            }

            MsgMessage msg = new MsgMessage();

            msg.MessageText = chat;
            msg.From        = from == null ? PlayerConstants.ServerPlayerID : from.PlayerID;
            msg.To          = to.PlayerID;
            msg.MessageType = action ? MsgMessage.MessageTypes.ActionMessage : MsgMessage.MessageTypes.ChatMessage;

            to.SendMessage(true, msg);

            MessageSent?.Invoke(this, args);
        }
 private void OnServerMessageSent(object sender, int bytesSent)
 {
     MessageSent?.Invoke(this, new ConnectionMessageEventArgs()
     {
         Source = UniqueId, Message = $"{bytesSent}", Type = MessageType.Text
     });
 }
Beispiel #13
0
        ////////////////////////////////////////////////////////////////////////////

        ////////////////////////////////////////////////////////////////////////////
        protected virtual void OnMessageSent(ConsoleMessageEventArgs e)
        {
            if (MessageSent != null)
            {
                MessageSent.Invoke(this, e);
            }
        }
Beispiel #14
0
        async Task StartRunningLoop(CancellationToken ctx)
        {
            while (_chatClient != null && !ctx.IsCancellationRequested)
            {
                try
                {
                    if (_conversation == null || string.IsNullOrEmpty(_conversation?.ConversationId))
                    {
                        throw new FieldAccessException(nameof(Conversation.ConversationId));
                    }

                    while (!string.IsNullOrEmpty(_channelAccount.Id) && _outputActivities.TryDequeue(out var outputActivity))
                    {
                        var response = await _chatClient.Conversations.PostActivityAsync(_conversation.ConversationId, outputActivity, ctx);

                        MessageSent?.Invoke(this, outputActivity.Text);
                    }
                }
                catch (Exception exception)
                {
                    Error?.Invoke(this, exception);
                }

                await Task.Delay(200, ctx).ConfigureAwait(false);
            }
        }
Beispiel #15
0
        private void HandleMessages()
        {
            while (Thread.CurrentThread.IsAlive)
            {
                if (hasMessages)
                {
                    int messageCount   = messageQueue.Count;
                    int messagesToTake = messageCount > MessagesToTakeFromQueueEachFrame
            ? MessagesToTakeFromQueueEachFrame
            : messageCount;

                    BaseMessage[] messages;
                    lock (messageQueue)
                    {
                        messages = messageQueue.Dequeue(messagesToTake);
                    }
                    foreach (var message in messages)
                    {
                        MessageSent?.Invoke(this, message);
                    }

                    hasMessages = messageQueue.Count > 0;
                }
                Thread.Sleep(16);
            }
        }
Beispiel #16
0
        protected virtual void OnError(string message)
        {
            var e = MessageEventArgs.Error(message);

            MessageSent?.Invoke(this, e);
            throw new InvalidOperationException();
        }
Beispiel #17
0
 void _sendThread()
 {
     Thread.CurrentThread.CurrentCulture   = new CultureInfo("en-US");
     Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
     while (ThreadsRunning)
     {
         try
         {
             if (outputString.Count > 0 && Connected)
             {
                 string message = OutputString;
                 lastmessage = message;
                 if (!String.IsNullOrEmpty(message))
                 {
                     byte[] buffer = Encoding.UTF8.GetBytes(message);
                     stream.Write(buffer, 0, buffer.Length);
                     MessageSent?.Invoke(this, new MessageSentEventArgs(message));
                 }
             }
         }
         catch
         {
             continue;
         }
         Thread.Sleep(100);
     }
 }
Beispiel #18
0
    // simple mail to 1 recepient w/o attachments
    public bool Send(string to, string subject, string body)
    {
        MessageID = Guid.NewGuid();

        using (var smtpClient = new SmtpClient()
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(SystemMailAddress, SystemMailFromPassword)
        })
        {
            using (var mailMsg = new MailMessage())
            {
                mailMsg.From       = new MailAddress(SystemMailAddress, SystemFromName);
                mailMsg.Subject    = subject;
                mailMsg.Body       = body;
                mailMsg.IsBodyHtml = true;
                mailMsg.To.Add(to);
                smtpClient.Credentials = new System.Net.NetworkCredential(SystemMailAddress, SystemMailFromPassword);
                smtpClient.Send(mailMsg);

                if (MessageSent != null)
                {
                    MessageSent.Invoke(MessageID, mailMsg);
                }
            }
        }
        return(true);
    }
Beispiel #19
0
 protected virtual void OnRatesUpdated(MessageEventArgs e)
 {
     if (MessageSent != null)
     {
         MessageSent.Invoke(this, e);
     }
 }
Beispiel #20
0
        static Chat()
        {
            ChatSubmitMessage.Subscribe(data =>
            {
                var eventArgs = new ChatMessageEventArgs(G.Sys.PlayerManager_.Current_.profile_.Name_, data.message_);
                MessageSent?.Invoke(null, eventArgs);
            });

            ChatMessage.Subscribe(data =>
            {
                Console.WriteLine(data.message_);

                var author = ExtractMessageAuthor(data.message_);

                if (author != G.Sys.PlayerManager_.Current_.profile_.Name_ && !IsSystemMessage(data.message_))
                {
                    var eventArgs = new ChatMessageEventArgs(author, ExtractMessageBody(data.message_));
                    MessageReceived?.Invoke(null, eventArgs);
                }
            });

            ToAllClientsRemotePlayerActionMessage.Subscribe(data =>
            {
                if (G.Sys.NetworkingManager_.IsOnline_)
                {
                    var nickname  = G.Sys.PlayerManager_.PlayerList_[data.index_].Username_;
                    var eventArgs = new ChatActionEventArgs(data.index_, nickname, data.message_);
                    ActionReceived?.Invoke(null, eventArgs);
                }
            });
        }
Beispiel #21
0
        public async ValueTask <bool> Send(Message message, HashSet <long> receivers)
        {
            using var context     = Context;
            message.ObjectId      = IdGenerator.CreateId();
            message.CreateUtcTime = DateTime.UtcNow;
            message.Receivers     = receivers.ToList();

            var messageBox = new MessageBox(context);

            context.BeginTran();
            try
            {
                if (!await messageBox.AddMessage(message) ||
                    !await messageBox.SendMessage(message.ObjectId, message.Receivers))
                {
                    context.RollbackTran();
                    return(false);
                }
                context.CommitTran();
                MessageSent?.Invoke(this, message);
                return(true);
            }
            catch (Exception e)
            {
                context.RollbackTran();
                throw;
            }
        }
Beispiel #22
0
 protected void onMessageSent(ClientConnection connection, Message msg)
 {
     this.control.Invoke((MethodInvoker)(() =>
     {
         MessageSent?.Invoke(this, msg);
     }));
 }
Beispiel #23
0
 public void SendMessage(string message)
 {
     _fridaDispatcher.BeginInvoke((Action)(() =>
     {
         _script.Post(message);
         MessageSent?.Invoke();
     }));
 }
Beispiel #24
0
        public async Task SendAsync(byte[] buffer, IPEndPoint endpoint)
        {
            if (SendAsynchronously)
            {
                await Task.Yield();
            }

            MessageSent?.Invoke(buffer, endpoint);
        }
Beispiel #25
0
        public void Start()
        {
            foreach (var sequence in GetMessageSequence())
            {
                MessageSent?.Invoke(this, new MessageSentEventArgs(sequence.Message));

                Thread.Sleep(sequence.WaitSpan);
            }
        }
Beispiel #26
0
        public void SendMessage(string message, NLog.LogLevel logLevel = null)
        {
            if (logLevel == null)
            {
                logLevel = NLog.LogLevel.Info;
            }

            MessageSent?.Invoke(message, logLevel);
        }
 /// <summary>
 /// Sends the oldest message in the queue to the CAN.
 /// </summary>
 private static void SendNextInQueue()
 {
     if (messageQueue.Count > 0)
     {
         int error             = 0;
         C4UFX.CANMessage mess = messageQueue.Dequeue();
         C4UFX.SendCANMess(0, 0, mess, out error);
         MessageSent?.Invoke(mess);
     }
 }
Beispiel #28
0
 private void SendMessage()
 {
     if (!tbInput.Text.IsNullOrWhitespace())
     {
         MessageSent?.Invoke(tbInput.Text.Trim());
         AppendMessageFromThisUser(tbInput.Text.Trim());
         tbInput.Text           = "";
         tbInput.SelectionStart = 0;
     }
 }
Beispiel #29
0
        /// <summary>
        /// Sends a message to the currently connected stranger.
        /// </summary>
        /// <param name="message">Message content to be sent.</param>
        public void SendMessage(string message)
        {
            if (IsReady && IsOpen && IsStrangerConnected)
            {
                SendPacket(new MessagePacket(message, CurrentContactUID));

                var eventArgs = new MessageEventArgs(new Message(message, -1, -1, MessageType.Chat));
                MessageSent?.Invoke(this, eventArgs);
                ActionID++;
            }
        }
Beispiel #30
0
 public void Send(Message message)
 {
     if (message == null)
     {
         return;
     }
     if (message.TargetId == Id)
     {
         SaveStateMessageIfNeeded(message);
     }
     MessageSent?.Invoke(message);
 }