Beispiel #1
0
        public async Task messagesGetHistory(IOutgoingMessage message)
        {
            try
            {
                var tmessage = (OutgoingMessage)message;

                var request = new HistoryRequest
                {
                    //offset = 0,
                    count = 1,
                    //user_id = "1556462",
                    peer_id = tmessage.peer_id,
                    //start_message_id = "0",
                    //rev = "1",
                    //extended =
                    //fields =
                    group_id = _options.groupId,
                };
                await vkService.sendRequest(request, "messages.getHistory", _options);
            }
            catch (Exception e)
            {
                _logger.Log(NLog.LogLevel.Error, e, "SendMessageAsync error");
            }
        }
        /// <inheritdoc />
        public void WriteToTransport(IOutgoingMessage <IOutgoingMessageType> message, ITransport transport, CancellationToken cancellationToken = default)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (transport == null)
            {
                throw new ArgumentNullException(nameof(transport));
            }
            if (!(message is EnableContinuousUpdatesMessage enableContinuousUpdatesMessage))
            {
                throw new ArgumentException($"Message is no {nameof(EnableContinuousUpdatesMessage)}.", nameof(message));
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Message size
            const int messageSize = 1 + sizeof(byte) + 4 * sizeof(ushort);

            // Allocate buffer
            Debug.Assert(messageSize <= 1024, "messageSize <= 1024");
            Span <byte> buffer = stackalloc byte[messageSize];

            // Message header
            buffer[0] = Id;

            // Enable?
            buffer[1] = (byte)(enableContinuousUpdatesMessage.Enable ? 1 : 0);

            // Rectangle
            Rectangle rectangle = enableContinuousUpdatesMessage.Rectangle;

            BinaryPrimitives.WriteUInt16BigEndian(buffer[2..], (ushort)rectangle.Position.X);
        /// <inheritdoc />
        public void WriteToTransport(IOutgoingMessage <IOutgoingMessageType> message, ITransport transport, CancellationToken cancellationToken = default)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (transport == null)
            {
                throw new ArgumentNullException(nameof(transport));
            }
            if (!(message is KeyEventMessage keyEventMessage))
            {
                throw new ArgumentException($"Message is no {nameof(KeyEventMessage)}.", nameof(message));
            }

            cancellationToken.ThrowIfCancellationRequested();

            Span <byte> buffer = stackalloc byte[8];

            // Message type
            buffer[0] = Id;

            // Down flag (followed by two bytes padding)
            buffer[1] = (byte)(keyEventMessage.DownFlag ? 1 : 0);

            // Keysym
            BinaryPrimitives.WriteUInt32BigEndian(buffer[4..], (uint)keyEventMessage.KeySymbol);
Beispiel #4
0
        /// <inheritdoc />
        public void WriteToTransport(IOutgoingMessage <IOutgoingMessageType> message, ITransport transport, CancellationToken cancellationToken = default)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (transport == null)
            {
                throw new ArgumentNullException(nameof(transport));
            }
            if (!(message is PointerEventMessage pointerEventMessage))
            {
                throw new ArgumentException($"Message is no {nameof(PointerEventMessage)}.", nameof(message));
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Get pointer position
            var posX = (ushort)Math.Max(0, pointerEventMessage.PointerPosition.X);
            var posY = (ushort)Math.Max(0, pointerEventMessage.PointerPosition.Y);

            Span <byte> buffer = stackalloc byte[6];

            // Message type
            buffer[0] = Id;

            // Pressed buttons mask
            buffer[1] = (byte)pointerEventMessage.PressedButtons;

            // Pointer position
            BinaryPrimitives.WriteUInt16BigEndian(buffer[2..], posX);
Beispiel #5
0
        public async Task <bool> SendMessageAsync(IOutgoingMessage message)
        {
            try
            {
                var tmessage = (OutgoingMessage)message;

                var urlBuilder = new UriBuilder(_url)
                {
                    Path  = "method/messages.send",
                    Query = $"group_id={_groupId}&access_token={_token}&v={_apiVersion}"
                };

                var values = new Dictionary <string, string>
                {
                    { "random_id", tmessage.random_id },
                    { "peer_id", tmessage.peer_id.ToString() },
                    { "message", tmessage.message },
                    // { "attachment", "364384447" }
                };

                var content  = new FormUrlEncodedContent(values);
                var response = await _httpClient.PostAsync(urlBuilder.Uri, content);

                var responseBody = await response.Content.ReadAsStringAsync();

                return(true);
            }
            catch (Exception e)
            {
                _logger.Log(NLog.LogLevel.Error, e, "send error");
                return(false);
            }
        }
        /// <inheritdoc />
        public void WriteToTransport(IOutgoingMessage <IOutgoingMessageType> message, ITransport transport, CancellationToken cancellationToken = default)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (transport == null)
            {
                throw new ArgumentNullException(nameof(transport));
            }
            if (!(message is SetDesktopSizeMessage setDesktopSizeMessage))
            {
                throw new ArgumentException($"Message is no {nameof(SetDesktopSizeMessage)}.", nameof(message));
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Execute the mutation
            (Size size, IImmutableSet <Screen> layout) = setDesktopSizeMessage.MutationFunc.Invoke(_state.RemoteFramebufferSize, _state.RemoteFramebufferLayout);

            // Calculate message size
            int messageSize = 2 + 2 * sizeof(ushort) + 2 + layout.Count * (sizeof(uint) + 4 * sizeof(ushort) + sizeof(uint));

            // Allocate buffer
            Span <byte> buffer = messageSize <= 1024 ? stackalloc byte[messageSize] : new byte[messageSize];

            // Message header
            buffer[0] = Id;
            buffer[1] = 0; // Padding

            // Size
            BinaryPrimitives.WriteUInt16BigEndian(buffer[2..], (ushort)size.Width);
Beispiel #7
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="message"></param>
 public void Broadcast(IOutgoingMessage message)
 {
     foreach (var peer in subscribersList)
     {
         peer.SendMessage(message, DeliveryMethod.Reliable);
     }
 }
        /// <summary>
        /// This version is used to forward an incoming request to a server
        /// </summary>
        public ServerRequestContext(
            IRequestContext requestContext,
            IPAddress serverIpAddress,
            ushort serverPort,
            Scheme scheme)
        {
            _log = requestContext.Log;

            _incoming = new IncomingMessage
            {
                Headers       = requestContext.Incoming.Headers,
                OnSendHeaders = requestContext.Incoming.OnSendHeaders,
                Content       = requestContext.Incoming.Content,
                ContentLength = requestContext.Incoming.ContentLength,

                Method        = requestContext.Incoming.Method,
                Scheme        = scheme,
                DomainName    = requestContext.Incoming.DomainName,
                Path          = requestContext.Incoming.Path,
                Query         = requestContext.Incoming.Query,
                SourceAddress = requestContext.Incoming.SourceAddress,
                SourcePort    = requestContext.Incoming.SourcePort,

                DestinationAddress = serverIpAddress,
                DestinationPort    = serverPort
            };

            _outgoing = requestContext.Outgoing;
        }
Beispiel #9
0
        /// <inheritdoc />
        public void WriteToTransport(IOutgoingMessage <IOutgoingMessageType> message, ITransport transport, CancellationToken cancellationToken = default)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (transport == null)
            {
                throw new ArgumentNullException(nameof(transport));
            }
            if (!(message is ClientFenceMessage clientFenceMessage))
            {
                throw new ArgumentException($"Message is no {nameof(ClientFenceMessage)}.", nameof(message));
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Message size
            int messageSize = 1 + 3 + sizeof(uint) + sizeof(byte) + clientFenceMessage.Payload.Length;

            // Allocate buffer
            Debug.Assert(messageSize <= 1024, "messageSize <= 1024");
            Span <byte> buffer = stackalloc byte[messageSize];

            // Message header
            buffer[0] = Id;

            // Padding
            buffer[1] = 0;
            buffer[2] = 0;
            buffer[3] = 0;

            // Flags
            BinaryPrimitives.WriteUInt32BigEndian(buffer[4..], (uint)clientFenceMessage.Flags);
Beispiel #10
0
 public Task SendAsync(IOutgoingMessage message, IReceiptBehavior receiptBehavior)
 {
     return
         (receiptBehavior.DecorateSendMessageTask(
              _transport.SendMessage(new OutgoingMessageAdapter(receiptBehavior.DecorateMessage(message),
                                                                _destination))));
 }
Beispiel #11
0
 /// <summary>
 /// Convert the message to a byte buffer.
 /// </summary>
 /// <param name="message">Message to be serialised.</param>
 /// <returns>Message serialised as a byte buffer</returns>
 internal static byte[] ToArray(IOutgoingMessage message)
 {
     using (var stream = new MemoryStream())
         using (var writer = new BinaryWriter(stream))
         {
             message.Write(writer);
             return(stream.ToArray());
         }
 }
        public void SendMQ(object obj)
        {
            client.Connect();
            IOutgoingMessage message = client.CreateMessage();

            message.MessageData = GeneralHelper.SerializeObject(obj);
            message.Send();
            client.Disconnect();
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="MQContent">消息内容</param>
        /// <param name="ServerName">接收端程序名,必须在服务端注册</param>
        public void SendMQ(string MQContent)
        {
            client.Connect();
            IOutgoingMessage message = client.CreateMessage();

            message.MessageData = Encoding.UTF8.GetBytes(MQContent);
            message.Send();
            client.Disconnect();
        }
Beispiel #14
0
        // An acked messages expects an ack to be sent from the server, if the ack message is not received in time the message will be sent again.
        // optimize wait time by only sending message again when waiting time > rtt
        public void SendAckedMessage(IOutgoingMessage messageToSend, byte messageAckIdToWaitFor, Action <byte[]> onAckMessageReceivedCallback)
        {
            IDisposable messageReceiveDisposable = udpClient.OnMessageReceive
                                                   .Where(message => message[0] == messageAckIdToWaitFor)
                                                   .Subscribe(OnMessageReceived);

            pendingAckMessages.Add(new AckMessageAwaitData(messageAckIdToWaitFor, messageReceiveDisposable, messageToSend, onAckMessageReceivedCallback));

            udpClient.SendMessage(messageToSend.GetBytes());
        }
Beispiel #15
0
        public override async Task SendMessageAsync(IChatSession sess, IOutgoingMessage msg)
        {
            if (!(sess is ChatSession))
            {
                throw new Exception("Bad chat session type");
            }
            var s = sess as ChatSession;

            switch (msg.Type)
            {
            case MsgOutType.Text:
            {
                var m = new TextMessage
                {
                    Text     = msg.Text,
                    Receiver = s.InternalChatId
                };
                await _cli.SendTextMessageAsync(m);

                break;
            }

            case MsgOutType.Keyboard:
            {
                var keyboardMsg = new KeyboardMessage
                {
                    Text          = msg.Text,
                    Receiver      = s.InternalChatId,
                    Keyboard      = GetViberKeyboard(msg.Keyboard.Buttons.ToArray()),
                    MinApiVersion = 3
                };
                await _cli.SendKeyboardMessageAsync(keyboardMsg);

                break;
            }

            case MsgOutType.Photo:
                break;

            case MsgOutType.Wait:
            {
                var m = new TextMessage
                {
                    Text     = $"Нагадування встановлено",
                    Receiver = s.InternalChatId
                };
                await _cli.SendTextMessageAsync(m);

                break;
            }

            default:
                break;
            }
        }
Beispiel #16
0
        /// <summary>
        /// Respond with a message
        /// </summary>
        /// <param name="message"></param>
        /// <param name="statusCode"></param>
        public void Respond(IOutgoingMessage message, ResponseStatus statusCode = ResponseStatus.Default)
        {
            message.Status = statusCode;

            if (AckResponseId.HasValue)
            {
                message.AckResponseId = AckResponseId.Value;
            }

            Peer.SendMessage(message, DeliveryMethod.Reliable);
        }
Beispiel #17
0
 public async Task <string> messagesGetConversationsAsync(IOutgoingMessage message)
 {
     try
     {
         return(await vkService.sendRequest(message, "messages.getConversations", _options));
     }
     catch (Exception e)
     {
         _logger.Log(NLog.LogLevel.Error, e, "SendMessageAsync error");
         return(null);
     }
 }
Beispiel #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        /// <param name="condition"></param>
        public void Broadcast(IOutgoingMessage message, Func <IPeer, bool> condition)
        {
            foreach (var peer in subscribersList)
            {
                if (!condition(peer))
                {
                    continue;
                }

                peer.SendMessage(message, DeliveryMethod.Reliable);
            }
        }
Beispiel #19
0
        /// <summary>
        /// Sends a message to peer
        /// </summary>
        /// <param name="message">Message to send</param>
        /// <param name="responseCallback">Callback method, which will be invoked when peer responds</param>
        /// <param name="timeoutSecs">If peer fails to respons within this time frame, callback will be invoked with timeout status</param>
        /// <param name="deliveryMethod">Delivery method</param>
        /// <returns></returns>
        public int SendMessage(IOutgoingMessage message, ResponseCallback responseCallback, int timeoutSecs, DeliveryMethod deliveryMethod)
        {
            if (!IsConnected)
            {
                responseCallback.Invoke(ResponseStatus.NotConnected, null);
                return(-1);
            }

            var id = RegisterAck(message, responseCallback, timeoutSecs);

            SendMessage(message, deliveryMethod);
            return(id);
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="MQContentList">消息内容数组</param>
        /// <param name="ServerName">接收端程序名,必须在服务端注册</param>
        public void SendMQ(List <string> MQContentList)
        {
            client.Connect();
            IOutgoingMessage message = client.CreateMessage();

            foreach (string mqc in MQContentList)
            {
                message.MessageData = Encoding.UTF8.GetBytes(mqc);

                message.Send();
            }
            client.Disconnect();
        }
Beispiel #21
0
        public async Task <bool> SendMessageAsync(IOutgoingMessage message)
        {
            try
            {
                var tmessage = (OutgoingMessage)message;

                return(await vkService.messagesSendAsync(tmessage, _groupId, _token, _apiVersion));
            }
            catch (Exception e)
            {
                _logger.Log(NLog.LogLevel.Error, e, "SendMessageAsync error");
                return(false);
            }
        }
Beispiel #22
0
        public async Task <string> sendMessageAsync(IOutgoingMessage message)
        {
            try
            {
                var tmessage = (OutgoingMessage)message;

                return(await vkService.sendRequest(tmessage, "messages.send", _options));
            }
            catch (Exception e)
            {
                _logger.Log(NLog.LogLevel.Error, e, "SendMessageAsync error");
                return(null);
            }
        }
Beispiel #23
0
        public Task SendMessageAsync(IOutgoingMessage message)
        {
            try
            {
                this.Socket.Send(message.GetOutData());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Environment.Exit(-1);
            }

            return(Task.CompletedTask);
        }
Beispiel #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static byte GenerateFlags(IOutgoingMessage message)
        {
            var flags = message.Flags;

            if (message.AckRequestId.HasValue)
            {
                flags |= (byte)MessageFlag.AckRequest;
            }

            if (message.AckResponseId.HasValue)
            {
                flags |= (byte)MessageFlag.AckResponse;
            }

            return(flags);
        }
Beispiel #25
0
        public override void SendMessage(IOutgoingMessage message, DeliveryMethod deliveryMethod)
        {
            if (delayedMessages != null)
            {
                lock (delayedMessages)
                {
                    if (delayedMessages != null)
                    {
                        delayedMessages.Enqueue(message.ToBytes());
                        return;
                    }
                }
            }

            socket.Send(message.ToBytes());
        }
Beispiel #26
0
        public override void SendMessage(IOutgoingMessage message, DeliveryMethod deliveryMethod)
        {
            if (_delayedMessages != null)
            {
                lock (_delayedMessages)
                {
                    if (_delayedMessages != null)
                    {
                        _delayedMessages.Enqueue(message.ToBytes());
                        return;
                    }
                }
            }

            _session.SendData(message.ToBytes());
        }
Beispiel #27
0
        /// <inheritdoc />
        public void EnqueueMessage <TMessageType>(IOutgoingMessage <TMessageType> message, CancellationToken cancellationToken = default)
            where TMessageType : class, IOutgoingMessageType
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (_disposed)
            {
                throw new ObjectDisposedException(nameof(RfbMessageSender));
            }

            cancellationToken.ThrowIfCancellationRequested();

            TMessageType messageType = GetAndCheckMessageType <TMessageType>();

            // Add message to queue
            _queue.Add(new QueueItem(message, messageType), cancellationToken);
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="MQContentList">消息内容数组</param>
        /// <param name="ServerNameList">接收端程序名数组,必须在服务端注册</param>
        public void SendMQ(List <string> MQContentList, List <string> ServerNameList)
        {
            if (MQContentList.Count == ServerNameList.Count)
            {
                client.Connect();

                IOutgoingMessage message = client.CreateMessage();

                for (int i = 0; i < MQContentList.Count; i++)
                {
                    message.DestinationApplicationName = ServerNameList[i];

                    message.MessageData = Encoding.UTF8.GetBytes(MQContentList[i]);

                    message.Send();
                }
                client.Disconnect();
            }
        }
Beispiel #29
0
        /// <summary>
        /// Adds the <paramref name="message"/> to the send queue and returns a <see cref="Task"/> that completes when the message was sent.
        /// </summary>
        /// <param name="message">The message to send.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <typeparam name="TMessageType">The type of the message.</typeparam>
        /// <remarks>Please ensure the outgoing message type is marked as being supported by both sides before sending it. See <see cref="RfbConnection.UsedMessageTypes"/>.</remarks>
        public Task SendMessageAsync <TMessageType>(IOutgoingMessage <TMessageType> message, CancellationToken cancellationToken = default)
            where TMessageType : class, IOutgoingMessageType
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            cancellationToken.ThrowIfCancellationRequested();

            RfbConnectionContext?connection = _activeConnection;

            if (connection?.MessageSender == null)
            {
                return(Task.CompletedTask);
            }

            return(connection.MessageSender.SendMessageAndWaitAsync(message, cancellationToken));
        }
Beispiel #30
0
        // This method will not catch exceptions so the BackgroundThread base class will receive them,
        // raise a "Failure" and trigger a reconnect.
        protected override void ThreadWorker(CancellationToken cancellationToken)
        {
            try
            {
                Debug.Assert(_context.Transport != null, "_context.Transport != null");
                ITransport transport = _context.Transport;

                // Iterate over all queued items (will block if the queue is empty)
                foreach (QueueItem queueItem in _queue.GetConsumingEnumerable(cancellationToken))
                {
                    IOutgoingMessage <IOutgoingMessageType> message = queueItem.Message;
                    IOutgoingMessageType messageType = queueItem.MessageType;

                    if (_logger.IsEnabled(LogLevel.Debug))
                    {
                        string?parametersOverview = message.GetParametersOverview();
                        _logger.LogDebug("Sending {messageName} message ({parameters})...", messageType.Name, parametersOverview ?? "no parameters");
                    }

                    try
                    {
                        // Write message to transport stream
                        messageType.WriteToTransport(message, transport, cancellationToken);
                        queueItem.CompletionSource?.SetResult(null);
                    }
                    catch (Exception ex)
                    {
                        // If something went wrong during sending, tell the waiting tasks about it (so for example the GUI doesn't wait forever).
                        queueItem.CompletionSource?.TrySetException(ex);

                        // Send-thread should still fail
                        throw;
                    }
                }
            }
            catch
            {
                // When the loop was canceled or failed, cancel all remaining queue items
                SetQueueCancelled();
                throw;
            }
        }
Beispiel #31
0
 public bool IsSameDestination(IOutgoingMessage other)
 {
     var msg = (Message)other;
     return msg != null && Object.Equals(TargetSilo, msg.TargetSilo);
 }
 /// <summary>
 /// Creates an instance of <see cref="PersistentHeaderDecorator"/>
 /// that wraps the given <paramref name="child"/>.
 /// </summary>
 /// <param name="child"></param>
 public PersistentHeaderDecorator(IOutgoingMessage child)
     : base(child)
 {
 }
 /// <summary>
 /// Decorates the given <paramref name="message"/> 
 /// with a <see cref="ReceiptHeaderDecorator"/>.
 /// </summary>
 /// <param name="message"></param>
 /// <returns></returns>
 public IOutgoingMessage DecorateMessage(IOutgoingMessage message)
 {
     return new ReceiptHeaderDecorator(message, _destination, Interlocked.Increment(ref _messageSequence));
 }
 public OutgoingMessageAdapter(IOutgoingMessage outgoingMessage, string destination)
 {
     _outgoingMessage = outgoingMessage;
     _destination = destination;
 }
 /// <summary>
 /// Creates an instance of <see cref="TransactionHeaderDecorator"/>
 /// for the given <paramref name="child"/> and <paramref name="transactionId"/>.
 /// </summary>
 /// <param name="child"></param>
 /// <param name="transactionId"></param>
 public TransactionHeaderDecorator(IOutgoingMessage child, int transactionId)
     : base(child)
 {
     _transactionId = transactionId;
 }
 public IOutgoingMessage DecorateMessage(IOutgoingMessage message)
 {
     return message;
 }
 /// <summary>
 /// Creates an instance of <see cref="HeaderDecorator"/>
 /// that wraps the given <paramref name="child"/>
 /// </summary>
 /// <param name="child"></param>
 protected HeaderDecorator(IOutgoingMessage child)
 {
     _child = child;
 }
 /// <summary>
 /// Creates an instance of <see cref="ReceiptHeaderDecorator"/>
 /// with the given parameters.
 /// 
 /// The header value will be the <paramref name="destination"/>
 /// and the <paramref name="messageSequence"/> joined with a period (".").
 /// </summary>
 /// <param name="message"></param>
 /// <param name="destination"></param>
 /// <param name="messageSequence"></param>
 public ReceiptHeaderDecorator(IOutgoingMessage message, string destination, long messageSequence)
     : base(message)
 {
     _destination = destination;
     _messageSequence = messageSequence;
 }