Exemplo n.º 1
0
        async void MessageReceived(byte[] buffer, IPEndPoint endpoint)
        {
            await DhtEngine.MainLoop;

            // Don't handle new messages if we have already stopped the dht engine.
            if (Listener.Status == ListenerStatus.NotListening)
            {
                return;
            }

            // I should check the IP address matches as well as the transaction id
            // FIXME: This should throw an exception if the message doesn't exist, we need to handle this
            // and return an error message (if that's what the spec allows)
            try {
                if (DhtMessageFactory.TryDecodeMessage((BEncodedDictionary)BEncodedValue.Decode(buffer, false), out DhtMessage message))
                {
                    Monitor.ReceiveMonitor.AddDelta(buffer.Length);
                    ReceiveQueue.Enqueue(new KeyValuePair <IPEndPoint, DhtMessage> (endpoint, message));
                }
            } catch (MessageException) {
                // Caused by bad transaction id usually - ignore
            } catch (Exception) {
                //throw new Exception("IP:" + endpoint.Address.ToString() + "bad transaction:" + e.Message);
            }
        }
Exemplo n.º 2
0
        protected virtual void OnReceive(TCPClient client, int numberOfBytesReceived)
        {
            if (numberOfBytesReceived <= 0)
            {
                this.Status = SocketStatus.SOCKET_STATUS_NO_CONNECT;
                this.OnDisconnect(client);
            }
            else
            {
#if DEBUG
                //CrestronConsole.PrintLine("{0}.OnReceive() numberOfBytesReceived = {1}, Enqueuing...", this.GetType().Name, numberOfBytesReceived);
#endif
                for (int b = 0; b < numberOfBytesReceived; b++)
                {
                    ReceiveQueue.Enqueue(client.IncomingDataBuffer[b]);
                    if (_receiveThread == null || _receiveThread.ThreadState == Thread.eThreadStates.ThreadFinished)
                    {
                        _receiveThread          = new Thread(ReceiveThreadProcess, null, Thread.eThreadStartOptions.CreateSuspended);
                        _receiveThread.Priority = Thread.eThreadPriority.UberPriority;
                        _receiveThread.Name     = string.Format("{0} Rx Handler", this.GetType().Name);
                        _receiveThread.Start();
                    }
                }

                if (client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
                {
                    client.ReceiveDataAsync(OnReceive);
                }
            }
        }
Exemplo n.º 3
0
 private void PortThread()
 {
     while (true)
     {
         if (_port.IsOpen)
         {
             try
             {
                 var receive = _port.ReadLine().Replace("\r", "").Replace("\n", "");
                 if (receive == _heartbeatPhrase)
                 {
                     LastHeartbeatAt = DateTime.Now;
                 }
                 else
                 {
                     ReceiveQueue.Enqueue(receive);
                 }
             }
             catch (Exception e)
             {
                 Debug.WriteLine("PortThread exception: {0}", e);
                 Thread.Sleep(1);
             }
         }
         else
         {
             Thread.Sleep(1);
         }
     }
 }
Exemplo n.º 4
0
        public virtual void MessageReceived(I2NPMessage msg, int recvdatasize)
        {
#if LOG_ALL_TUNNEL_TRANSFER
            Logging.LogDebug($"{this}: MessageReceived {msg.Message}");
#endif
            Bandwidth.DataReceived(recvdatasize);

            //Logging.LogDebug( $"{this}: MessageReceived {msg.MessageType} TDM len {recvsize}" );
            ReceiveQueue.Enqueue(msg);
        }
Exemplo n.º 5
0
 private void M_SocketManager_ReceiveClientData(Net.AsyncUserToken token, byte[] buff)
 {
     if (buff.Length > 0 && buff[0] == 0x5a)
     {
         ReceiveQueue.Enqueue(new WHQueueModel(buff, token.IPAddress.ToString()));
         string vOutInfo = string.Format("电源收到一组数据,IP地址({0}):{1}", token.IPAddress.ToString(), BitConverter.ToString(buff));
         Console.WriteLine(vOutInfo);
         LogHelper.WriteLog_Debug(typeof(PowerControl), vOutInfo);
     }
 }
Exemplo n.º 6
0
        public void EnqueueTest1()
        {
            ReceiveQueue target     = new ReceiveQueue(); // TODO: 初始化为适当的值
            IntPtr       byteBuffer = new IntPtr();       // TODO: 初始化为适当的值
            long         iOffset    = 0;                  // TODO: 初始化为适当的值
            long         iSize      = 0;                  // TODO: 初始化为适当的值

            target.Enqueue(byteBuffer, iOffset, iSize);
            Assert.Inconclusive("无法验证不返回值的方法。");
        }
Exemplo n.º 7
0
        /// <summary>
        /// Receive from one of the contained streams
        /// </summary>
        /// <param name="ct"></param>
        /// <returns></returns>
        public async Task ReceiveAsync(CancellationToken ct)
        {
            if (!Links.Any())
            {
                throw new SocketException(SocketError.Closed);
            }

            // Fill receive queue from any of the link's receive queue.  If queue is empty
            // replenish it from all streams...
            Message message;

            while (true)
            {
                foreach (var link in Links)
                {
                    while (link.ReceiveQueue.TryDequeue(out message))
                    {
                        if (message.TypeId == MessageContent.Close)
                        {
                            // Remote side closed, close link
                            Links.Remove(link);
                            try {
                                await link.CloseAsync(CancellationToken.None).ConfigureAwait(false);
                            }
                            catch { }

                            if (!Links.Any())
                            {
                                throw new SocketException("Remote side closed",
                                                          null, SocketError.Closed);
                            }
                        }
                        else
                        {
                            ReceiveQueue.Enqueue(message);
                        }
                    }
                }
                if (ReceiveQueue.Any())
                {
                    return;
                }
                else
                {
                    try {
                        var tasks = Links.Select(i => i.ReceiveAsync(ct));
                        await Task.WhenAny(tasks).ConfigureAwait(false);
                    }
                    catch (AggregateException ae) {
                        throw new SocketException("Receive await failed",
                                                  ae, ae.GetSocketError());
                    }
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Process new GameMessage from MessageController
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnMessageControllerNewMessageAvailable(object sender, GameMessageEventArgs e)
        {
            if (e.Message is LoginModeMessage)
            {
                HandleLoginModeMessage((LoginModeMessage)e.Message);
            }

            else if (e.Message is GameModeMessage)
            {
                HandleGameModeMessage((GameModeMessage)e.Message);
            }

            // Add the message to the received Message queue
            ReceiveQueue.Enqueue(e.Message);
        }
Exemplo n.º 9
0
        public void BinaryListenTask( )
        {
            try
            {
                byte currentSequence = 0;
                while (IsRunning)
                {
                    if (UnderlyingStream.ReadByte( ) == DatagramHeaderInt)
                    {
                        byte sequence = ( byte )UnderlyingStream.ReadByte( );

                        if (sequence == currentSequence)
                        {
                            currentSequence++;
                        }
                        else
                        {
                            //Todo:???
                        }

                        BinaryDatagramType type = ( BinaryDatagramType )( byte )UnderlyingStream.ReadByte( );                               //todo:if not throw

                        byte crc = ( byte )UnderlyingStream.ReadByte( );

                        byte length = ( byte )UnderlyingStream.ReadByte( );

                        byte [] data = new byte[length];

                        UnderlyingStream.Read(data, 0, length);

                        if (data.CaluCrc8( ) == crc)
                        {
                            if (Datagram.Parse(type, data) is ReceiveDatagram datagram)
                            {
                                ReceiveQueue.Enqueue(datagram);
                            }
                        }
                        else
                        {
                            //todo:Warning?
                        }
                    }
                }
            }
            catch (ThreadAbortException)
            {
            }
        }
            /// <summary>
            /// Sync Receive producer loop
            /// </summary>
            /// <param name="stream"></param>
            /// <param name="ct"></param>
            private void ReceiveProducer(CancellationToken ct)
            {
                Message message;

                while (true)
                {
                    try {
                        TaskCompletionSource <bool> tcs = null;
                        if (_consumerQueue.TryTake(out tcs, -1, ct))
                        {
                            if (!tcs.Task.IsCanceled)
                            {
                                try {
                                    message = _codec.ReadAsync <Message>(ct).Result;
                                    ReceiveQueue.Enqueue(message);
                                    if (message.TypeId == MessageContent.Close)
                                    {
                                        // Remote side closed, close the stream
                                        _open.Cancel();
                                        break;
                                    }
                                }
                                catch (Exception e) {
                                    ProxyEventSource.Log.StreamException(
                                        this, _codec.Stream, e);
                                    // Exit
                                    break;
                                }
                                finally {
                                    // Caller will retry if the queue is empty
                                    tcs.TrySetResult(true);
                                }
                            }
                        }
                    }
                    catch (OperationCanceledException) {
                        // Stream closing
                        break;
                    }
                    if (_streaming.IsCancellationRequested ||
                        _open.IsCancellationRequested ||
                        _consumerQueue.IsAddingCompleted)
                    {
                        break;
                    }
                }
            }
Exemplo n.º 11
0
        /// <summary>
        /// Process new GameMessage from MessageController
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnMessageControllerNewMessageAvailable(object sender, GameMessageEventArgs e)
        {
            // Internally process some of the messages  that are linked to the connection
            switch (messageController.Mode)
            {
            case ProtocolMode.Login:
                HandleLoginModeMessage(e.Message);
                break;

            case ProtocolMode.Game:
                HandleGameModeMessage(e.Message);
                break;
            }

            // Add the message to the received Message queue
            ReceiveQueue.Enqueue(e.Message);
        }
Exemplo n.º 12
0
        // the thread function
        void ReceiveThreadFunction(string ip, int port)
        {
            // absolutely must wrap with try/catch, otherwise thread
            // exceptions are silent
            try {
                // connect (blocking)
                client.Connect(ip, port);
                _connecting = false;

                // start send thread only after connected
                _sendThread = new Thread(() => { SendLoop(0, client, sendQueue, sendPending); });
                _sendThread.IsBackground = true;
                _sendThread.Start();

                // run the receive loop
                ReceiveLoop(0, client, ReceiveQueue, MaxMessageSize);
            } catch (SocketException exception) {
                // this happens if (for example) the ip address is correct
                // but there is no server running on that ip/port
                // add 'Disconnected' event to message queue so that the caller
                // knows that the Connect failed. otherwise they will never know
                ReceiveQueue.Enqueue(new Packet(0, PacketType.Disconnection, null));
                throw new Exception("Client Recv: failed to connect to ip=" + ip + " port=" + port + " reason=" +
                                    exception);
            } catch (Exception exception) {
                // something went wrong. probably important.
                throw new Exception("Client Recv Exception: " + exception);
            }

            // sendthread might be waiting on ManualResetEvent,
            // so let's make sure to end it if the connection
            // closed.
            // otherwise the send thread would only end if it's
            // actually sending data while the connection is
            // closed.
            _sendThread?.Interrupt();

            // Connect might have failed. thread might have been closed.
            // let's reset connecting state no matter what.
            _connecting = false;

            // if we got here then we are done. ReceiveLoop cleans up already,
            // but we may never get there if connect fails. so let's clean up
            // here too.
            client.Close();
        }
Exemplo n.º 13
0
    private async void RunReceive()
    {
        Debug.Log("WebSocket Message Receiver looping.");
        string result;

        while (true)
        {
            result = await Receive();

            if (result != null && result.Length > 0)
            {
                ReceiveQueue.Enqueue(result);
            }
            else
            {
                Task.Delay(50).Wait();
            }
        }
    }
Exemplo n.º 14
0
        public void XmlListenTask( )
        {
            try
            {
                StreamReader reader = new StreamReader(UnderlyingStream);

                while (IsRunning)
                {
                    string datagramString = reader.ReadLine( );

                    XElement element = XElement.Parse(datagramString);

                    if (Datagram.Parse(element) is ReceiveDatagram datagram)
                    {
                        ReceiveQueue.Enqueue(datagram);
                    }
                }
            }
            catch (ThreadAbortException)
            {
            }
        }
Exemplo n.º 15
0
        async void MessageReceived(byte[] buffer, IPEndPoint endpoint)
        {
            await DhtEngine.MainLoop;

            // I should check the IP address matches as well as the transaction id
            // FIXME: This should throw an exception if the message doesn't exist, we need to handle this
            // and return an error message (if that's what the spec allows)
            try
            {
                DhtMessage message;
                if (DhtMessageFactory.TryDecodeMessage((BEncodedDictionary)BEncodedValue.Decode(buffer, 0, buffer.Length, false), out message))
                {
                    ReceiveQueue.Enqueue(new KeyValuePair <IPEndPoint, DhtMessage>(endpoint, message));
                }
            }
            catch (MessageException)
            {
                // Caused by bad transaction id usually - ignore
            }
            catch (Exception)
            {
                //throw new Exception("IP:" + endpoint.Address.ToString() + "bad transaction:" + e.Message);
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Receive from one of the contained streams
        /// </summary>
        /// <param name="ct"></param>
        /// <returns></returns>
        public async Task ReceiveAsync(CancellationToken ct)
        {
            if (!Links.Any())
            {
                throw new SocketException(SocketError.Closed);
            }

            // Fill receive queue from any of the link's receive queue.  If queue is empty
            // replenish it from all streams...
            while (true)
            {
                foreach (var link in Links)
                {
                    Message message;
                    var     queue = link.ReceiveQueue;
                    if (queue == null)
                    {
                        Links.Remove(link);
                    }
                    else
                    {
                        while (queue.TryDequeue(out message))
                        {
                            if (message.TypeId == MessageContent.Close)
                            {
                                // Remote side closed, close link
                                Links.Remove(link);
                                try {
                                    await link.CloseAsync(ct).ConfigureAwait(false);
                                }
                                catch { }
                            }
                            else
                            {
                                ReceiveQueue.Enqueue(message);
                            }
                        }
                    }
                    if (!Links.Any())
                    {
                        throw new SocketException("Remote side closed",
                                                  null, SocketError.Closed);
                    }
                }
                if (ReceiveQueue.Any())
                {
                    return;
                }
                else
                {
                    try {
                        var tasks    = Links.Select(i => i.ReceiveAsync(ct));
                        var selected = await Task.WhenAny(tasks).ConfigureAwait(false);

                        await selected.ConfigureAwait(false);
                    }
                    catch (OperationCanceledException) {
                        throw;
                    }
                    catch (Exception e) {
                        ct.ThrowIfCancellationRequested();
                        throw new SocketException("Receive await failed",
                                                  e, e.GetSocketError());
                    }
                }
            }
        }