Exemplo n.º 1
0
        private void BlockchainMessageHandler(Socket socket)
        {
            Task.Run(() =>
            {
                while (true)
                {
                    messageManualReset.Reset();

                    StateObject state = new StateObject
                    {
                        workSocket = socket
                    };

                    byte[] messageType = new byte[1];
                    socket.Receive(messageType);

                    AsyncCallback handler = HandleTransactionData;

                    if ((MessageType)messageType.First() == MessageType.Blockchain)
                    {
                        handler = HandleBlockchainData;
                    }
                    else if ((MessageType)messageType.First() == MessageType.Transaction)
                    {
                        handler = HandleTransactionData;
                    }
                    else if ((MessageType)messageType.First() == MessageType.ClearTransaction)
                    {
                        using (var scope = _serviceProvider.CreateScope())
                        {
                            _transactionPoolService = scope.ServiceProvider.GetService <TransactionPoolService>();
                            _transactionPoolService.ClearPool();
                            messageManualReset.Set();
                            continue;
                        }
                    }

                    byte[] bufferSize = new byte[4];
                    socket.Receive(bufferSize);

                    //Little Endian
                    state.BufferSize = BitConverter.ToInt32(bufferSize.Reverse().ToArray());

                    try
                    {
                        socket.BeginReceive(state.buffer, 0, state.BufferSize, SocketFlags.None, handler, state);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                    finally
                    {
                        messageManualReset.WaitOne();
                    }
                }
            });
        }