コード例 #1
0
        /// <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);
        }
コード例 #2
0
 public void SendCommand(Message message)
 {
     try
     {
         SendingMessage?.Invoke(message);
     }
     catch (Exception ex)
     {
         LogOutput.Instance.Write(ex);
     }
     _server.SendCommand(message.Command + ":" + message.Content);
 }
コード例 #3
0
ファイル: Client.cs プロジェクト: SermanVS/SI
 /// <summary>
 /// Отправка сообщения
 /// </summary>
 /// <param name="text">Текст сообщения</param>
 /// <param name="isSystem">Системное ли</param>
 /// <param name="receiver">Получатель</param>
 /// <param name="isPrivate">Приватное ли</param>
 public void SendMessage(string text, bool isSystem = true, string receiver = Constants.Everybody, bool isPrivate = false)
 {
     SendingMessage?.Invoke(this, new Message(text, Name, receiver, isSystem, isPrivate));
 }