Example #1
0
        private Envelope ReadEnvelope()
        {
            var date      = ReadString();
            var subject   = ReadString();
            var from      = ReadMailAddressCollection();
            var sender    = ReadMailAddressCollection();
            var replyTo   = ReadMailAddressCollection();
            var to        = ReadMailAddressCollection();
            var cc        = ReadMailAddressCollection();
            var bcc       = ReadMailAddressCollection();
            var inReplyTo = ReadString();
            var messageId = ReadString();

            return(new Envelope
            {
                Bcc = bcc,
                Cc = cc,
                Date = HeaderFieldParser.ParseDate(date),
                From = from.FirstOrDefault(),
                InReplyTo = StringDecoder.Decode(inReplyTo, true),
                MessageId = messageId,
                ReplyTo = replyTo,
                Sender = sender.FirstOrDefault(),
                Subject = StringDecoder.Decode(subject, true),
                To = to
            });
        }
Example #2
0
        static async Task RunServerAsync()
        {
            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();

            var STRING_ENCODER = new StringEncoder();
            var STRING_DECODER = new StringDecoder();
            var SERVER_HANDLER = new ChatServerHandler();

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler(LogLevel.INFO))
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(STRING_ENCODER, STRING_DECODER, SERVER_HANDLER);
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(8080);

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
        public static MailAddress ParseMailAddress(string value)
        {
            int num = value.LastIndexOf("<", StringComparison.Ordinal);

            if (num < 0)
            {
                return(new MailAddress(string.Empty, value.Trim()));
            }

            string address = value.Substring(num).Trim().TrimStart('<').TrimEnd('>');

            if (string.IsNullOrEmpty(address))
            {
                return(null);
            }

            string displayName = "";

            if (num >= 1)
            {
                displayName = value.Substring(0, num - 1).Trim();
            }

            return(new MailAddress(StringDecoder.Decode(displayName, true).Trim().Trim(new[] { ' ', '<', '>', '\r', '\n' }), address));
        }
Example #4
0
        void UpdateAssemblyPanel()
        {
            lstView_Dissassembly.Items.Clear();
            int rows = 5;
            int PC   = Ada.PC;

            for (int i = PC - 4 * rows; i < PC + 4 * rows; i += 4)
            {
                if (i < 0 || i > Ada.RAM.MemoryArray.Length)
                {
                    LstStruct empty = new LstStruct
                    {
                        Address     = "0x" + i.ToString("X8"),
                        Values      = "",
                        Instruction = ""
                    };
                    continue;
                }

                int instCode = Ada.RAM.ReadWord(i);

                LstStruct row = new LstStruct
                {
                    Address     = "0x" + i.ToString("X8"),
                    Values      = StringDecoder.Decode(instCode, Ada.Registers, Ada.RAM, Ada.Flags, i),
                    Instruction = instCode.ToString("X8")
                };
                lstView_Dissassembly.Items.Add(row);
            }
            lstView_Dissassembly.SelectedIndex = rows;
        }
Example #5
0
        public bool Initialize()
        {
            Log?.Verbose(className, "Initialize", "Initializing Cxp Server Channel");

            channelHandler = CreateChannelHandler();
            if (channelHandler == null)
            {
                Log?.Information(className, "Initialize", "Failed to Initialize Cxp Server Channel");
                return(false);
            }


            bootstrap = new Bootstrap();
            group     = new MultithreadEventLoopGroup();
            encoder   = new StringEncoder();
            decoder   = new StringDecoder();

            bootstrap
            .Group(group)
            .Channel <TcpSocketChannel>()
            .Option(ChannelOption.TcpNodelay, true)
            .Handler(channelHandler);

            Log?.Information(className, "Initialize", "Cxp Server Channel Initialized");
            return(true);
        }
Example #6
0
        private ContentDisposition ReadDisposition()
        {
            SkipSpaces();
            var  sb = new StringBuilder();
            char currentChar;

            while ((currentChar = (char)_reader.Read()) != '(')
            {
                sb.Append(currentChar);
                if (sb.ToString() == "NIL")
                {
                    return(null);
                }
            }
            var type        = ReadString().ToLower();
            var paramaters  = ReadParameterList();
            var disposition = new ContentDisposition(type);

            foreach (var paramater in paramaters)
            {
                switch (paramater.Key)
                {
                case "filename":
                case "name":
                    disposition.FileName = StringDecoder.Decode(paramater.Value, true);
                    break;
                }
            }

            SkipSpaces();
            _reader.Read(); // read ')'
            SkipSpaces();
            return(disposition);
        }
Example #7
0
        static async Task RunServerAsync(int port)
        {
            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();

            var stringEncoder = new StringEncoder();
            var stringDecoder = new StringDecoder();
            var serverHandler = new ServerHandler(GameCore);

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler(LogLevel.INFO))
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    var pipeline = channel.Pipeline;

                    pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(stringEncoder, stringDecoder, serverHandler);
                }));

                var bootstrapChannel = await bootstrap.BindAsync(port);

                GameCore.RunContainers();
                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
Example #8
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static char[] decode(String charsetName, byte[] ba, int off, int len) throws java.io.UnsupportedEncodingException
        internal static char[] Decode(String charsetName, sbyte[] ba, int off, int len)
        {
            StringDecoder sd  = Deref(Decoder);
            String        csn = (charsetName == null) ? "ISO-8859-1" : charsetName;

            if ((sd == null) || !(csn.Equals(sd.RequestedCharsetName()) || csn.Equals(sd.CharsetName())))
            {
                sd = null;
                try
                {
                    Charset cs = LookupCharset(csn);
                    if (cs != null)
                    {
                        sd = new StringDecoder(cs, csn);
                    }
                }
                catch (IllegalCharsetNameException)
                {
                }
                if (sd == null)
                {
                    throw new UnsupportedEncodingException(csn);
                }
                Set(Decoder, sd);
            }
            return(sd.Decode(ba, off, len));
        }
Example #9
0
        public void Receive_one_message()
        {
            var slice1    = new BufferSlice(new byte[65535], 0, 65535);
            var encoder1  = new StringEncoder();
            var decoder1  = new StringDecoder();
            var expected  = "Hello".PadRight(5000);
            var outBuffer = new byte[expected.Length + 4];

            BitConverter2.GetBytes(expected.Length, outBuffer, 0);
            Encoding.UTF8.GetBytes(expected, 0, expected.Length, outBuffer, 4);
            object actual = null;
            var    evt    = new ManualResetEvent(false);
            var    stream = new SslStream(new NetworkStream(_helper.Server));

            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);

            var sut1 = CreateClientChannel(slice1, encoder1, decoder1);

            sut1.MessageReceived = (channel, message) =>
            {
                actual = message;
                evt.Set();
            };
            sut1.Assign(_helper.Client);
            evt.WaitOne(500); // wait on authentication
            evt.Reset();
            stream.Write(outBuffer);

            evt.WaitOne(500).Should().BeTrue();
            actual.Should().Be(expected);
        }
Example #10
0
        public void TestDecodeString(string encodedString, string expected)
        {
            var stringDecoder = new StringDecoder();
            var actual        = stringDecoder.DecodeString(encodedString);

            Assert.AreEqual(expected, actual);
        }
        public void send_message()
        {
            var slice   = new BufferSlice(new byte[65535], 0, 65535);
            var encoder = new StringEncoder();
            var decoder = new StringDecoder();

            var sut = CreateClientChannel(slice, encoder, decoder);

            sut.MessageReceived += (channel, message) =>
            {
            };
            var stream = new SslStream(new NetworkStream(_helper.Server));

            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);
            sut.Assign(_helper.Client);
            sut.Send("Hello world");

            //i do not know why this loop is required.
            //for some reason the send message is divided into two tcp packets
            //when using SslStream.
            var bytesReceived = 0;
            var buf           = new byte[65535];

            while (bytesReceived < 15)
            {
                bytesReceived += stream.Read(buf, bytesReceived, 15);
            }

            var actual = Encoding.ASCII.GetString(buf, 4, bytesReceived - 4); // string encoder have a length header.

            actual.Should().Be("Hello world");
        }
        public static string AsEncodedQueryString(this NameValueCollection collection)
        {
            var nameValueStrings =
                from string name in collection
                where !string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(collection[name])
                select string.Concat(name, "=", StringDecoder.Encode(collection[name]));

            return(string.Join("&", nameValueStrings));
        }
Example #13
0
        /// <summary>
        /// This method is called, when the Listener receives information.
        /// The received message is the parameter of the function.
        /// This method changes the values of the outputs.
        /// </summary>
        public async void ReceivedInformation(string request)
        {
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                var dictionary = StringDecoder.stringToDictionary(request);

                dictionary.ToList().ForEach(pair => _outputs[pair.Key].Text = pair.Value.ToString());
            });
        }
        public bool Download()
        {
            if (Downloaded)
            {
                return(true);
            }

            //ContentStream = new MemoryStream();
            // _writer = new StreamWriter(ContentStream);

            Encoding encoding = null;

            if (ContentType != null && ContentType.CharSet != null)
            {
                try
                {
                    encoding = Encoding.GetEncoding(ContentType.CharSet);
                }
                catch
                {
                }
            }
            else if (_message.ContentType != null && _message.ContentType.CharSet != null)
            {
                try
                {
                    encoding = Encoding.GetEncoding(_message.ContentType.CharSet);
                }
                catch
                {
                }
            }

            IList <string> data = new List <string>();

            _contentBuilder = new StringBuilder();

            bool result =
                _client.SendAndReceive(
                    string.Format(ImapCommands.Fetch, _message.UId,
                                  string.Format("BODY.PEEK[{0}.MIME] BODY.PEEK[{0}]", ContentNumber)), ref data,
                    this, encoding);

            //_writer.Flush();

            _fetchProgress = _fetchProgress | MessageFetchState.Body | MessageFetchState.Headers;

            ContentStream = _contentBuilder.ToString();

            if (ContentTransferEncoding == ContentTransferEncoding.QuotedPrintable && !string.IsNullOrEmpty(ContentStream))
            {
                ContentStream = StringDecoder.DecodeQuotedPrintable(ContentStream, encoding);
            }

            return(result);
        }
Example #15
0
 void initDecoders()
 {
     myDecoders[typeof(String)]    = new StringDecoder();
     myDecoders[typeof(UInt32)]    = new NumberDecoder <UInt32>();
     myDecoders[typeof(Int32)]     = new NumberDecoder <Int32>();
     myDecoders[typeof(UInt64)]    = new NumberDecoder <UInt64>();
     myDecoders[typeof(Int64)]     = new NumberDecoder <Int64>();
     myDecoders[typeof(float)]     = new NumberDecoder <float>();
     myDecoders[typeof(double)]    = new NumberDecoder <double>();
     myDecoders[typeof(bool)]      = new BoolDecoder();
     myDecoders[typeof(LuaObject)] = new LuaObjectDecoder();
 }
        public async Task StartAsync()
        {
            string methodName = MethodBase.GetCurrentMethod().Name;

            bossGroup   = new MultithreadEventLoopGroup(1);
            workerGroup = new MultithreadEventLoopGroup();

            var encoder = new StringEncoder();
            var decoder = new StringDecoder();

            try
            {
                bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workerGroup);
                bootstrap.Channel <TcpServerSocketChannel>();
                bootstrap
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler("SRV-LSTN"))
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (configuration.EnableTls)
                    {
                        X509Certificate2 tlsCertificate = GetCertificate();
                        if (tlsCertificate != null)
                        {
                            pipeline.AddLast("tls", TlsHandler.Server(tlsCertificate));
                        }
                        else
                        {
                            Log?.Error(className, methodName, "Certificate not found");
                        }
                    }


                    pipeline.AddLast("encoder", encoder);
                    pipeline.AddLast("decoder", decoder);

                    handler = new ServerChannelHandler();
                    //handler.ClientChannelManager = ClientChannelManager;
                    handler.ChannelHandler = ServerChannelHandler;
                    handler.Log            = Log;

                    pipeline.AddLast("handler", handler);
                }));

                boundChannel = await bootstrap.BindAsync(configuration.Port);
            }
            catch (Exception ex)
            {
                Log?.Error(className, methodName, ex.ToString());
            }
        }
Example #17
0
        static async Task RunServerAsync()
        {
            var logLevel = LogLevel.INFO;

            InternalLoggerFactory.DefaultFactory.AddProvider(new ConsoleLoggerProvider((s, level) => true, false));

            var serverPort = 8080;

            var bossGroup   = new MultithreadEventLoopGroup(1); //  accepts an incoming connection
            var workerGroup = new MultithreadEventLoopGroup();  // handles the traffic of the accepted connection once the boss accepts the connection and registers the accepted connection to the worker

            var encoder = new StringEncoder();
            var decoder = new StringDecoder();
            var helloWorldServerHandler = new HelloWorldServerHandler();

            try
            {
                var bootstrap = new ServerBootstrap();

                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)     // maximum queue length for incoming connection
                .Handler(new LoggingHandler(logLevel))
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    // handler evaluation order is 1, 2, 3, 4, 5 for inbound data and 5, 4, 3, 2, 1 for outbound

                    // The DelimiterBasedFrameDecoder splits the data stream into frames (individual messages e.g. strings ) and do not allow requests longer than n chars.
                    // It is required to use a frame decoder suchs as DelimiterBasedFrameDecoder or LineBasedFrameDecoder before the StringDecoder.
                    pipeline.AddLast("1", new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast("2", encoder);
                    pipeline.AddLast("3", decoder);
                    pipeline.AddLast("4", new CountCharsServerHandler());
                    //pipeline.AddLast("4½", new HasUpperCharsServerHandler());
                    pipeline.AddLast("5", helloWorldServerHandler);
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(serverPort);

                Console.WriteLine("Let us test the server in a command prompt");
                Console.WriteLine($"\n telnet localhost {serverPort}");
                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
Example #18
0
        private void Cleanup()
        {
            if (group != null)
            {
                group.ShutdownGracefullyAsync();
            }

            group          = null;
            encoder        = null;
            decoder        = null;
            channelHandler = null;
            bootstrap      = null;
        }
Example #19
0
        private ContentDisposition ReadDisposition()
        {
            SkipSpaces();
            var  sb = new StringBuilder();
            char currentChar;

            while ((currentChar = (char)_reader.Read()) != '(')
            {
                sb.Append(currentChar);
                if (sb.ToString() == "NIL")
                {
                    return(null);
                }
                if (currentChar == Convert.ToChar(65535))
                {
                    return(null);
                }
            }
            var type       = ReadString().ToLower();
            var paramaters = ReadParameterList();

            ContentDisposition disposition = null;

            try
            {
                disposition = new ContentDisposition(type);

                foreach (var paramater in paramaters)
                {
                    switch (paramater.Key)
                    {
                    case "filename":
                    case "name":
                        disposition.FileName = StringDecoder.Decode(paramater.Value, true);
                        break;
                    }
                }

                SkipSpaces();
                _reader.Read(); // read ')'
                SkipSpaces();
            }
            catch (Exception ex)
            {
                //EventLog.WriteEntry("purgeSource", ex.ToString());
                //throw new Exception("Failed on: " + type, ex);
            }


            return(disposition);
        }
Example #20
0
        static async Task Main(string[] args)
        {
            ExampleHelper.SetConsoleLogger();

            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();

            var stringEncoder = new StringEncoder();
            var stringDecoder = new StringDecoder();
            var serverHandler = new SecureChatServerHandler();

            X509Certificate2 tlsCertificate = null;

            if (ServerSettings.IsSsl)
            {
                tlsCertificate = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
            }

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler("LSTN"))
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (tlsCertificate != null)
                    {
                        pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                    }

                    pipeline.AddLast(new LoggingHandler("CONN"));
                    pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(stringEncoder, stringDecoder, serverHandler);
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(ServerSettings.Port);

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
Example #21
0
        static async Task RunServerAsync()
        {
            ExampleHelper.SetConsoleLogger();

            var STRING_ENCODER = new StringEncoder();
            var STRING_DECODER = new StringDecoder();


            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();
            X509Certificate2 tlsCertificate = null;

            if (ServerSettings.IsSsl)
            {
                tlsCertificate = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
            }
            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler("LSTN"))
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (tlsCertificate != null)
                    {
                        pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                    }
                    pipeline.AddLast(new LoggingHandler("CONN"));
                    pipeline.AddLast(new IdleStateHandler(10, 0, 0));
                    pipeline.AddLast(new MyLengthFieldBasedFrameDecoder(ByteOrder.LittleEndian, 1024 * 4, 1, 4, -5, 0, true));
                    //pipeline.AddLast(new DelimiterBasedFrameDecoder(1024*4,Unpooled.WrappedBuffer( new byte[] { (byte)'!' } )));
                    pipeline.AddLast(new MyLengthFieldBasedFrameEncoder(), STRING_DECODER, new EchoServerHandler());
                    pipeline.AddLast(new HeartBeatServerHandler());
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(ServerSettings.Port);

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
        public unsafe void DecoderTest()
        {
            //string str = "abcdefghijklmnop\u0135";
            string str = "\u0135\u0135\u0135\u0135\u0135";

            var decodeBuffer = new ArraySegment<char>(new char[3]);
            StringDecoder decoder = new StringDecoder(decodeBuffer);

            decoder.Decode(new ArraySegment<byte>(Encoding.UTF8.GetBytes(str)));

            var decodedString = decoder.ToString();
            Console.WriteLine(decodedString);
            Assert.AreEqual(str, decodedString);
        }
Example #23
0
        private async void InitializeAsync(int port, BasedFrameDecoderKind kind)
        {
            _bootstrap = await Task.Run(() =>
            {
                try
                {
                    var bootstrap = new ServerBootstrap()
                                    .Group(_bossGroup, _workGroup)
                                    .Channel <TcpServerSocketChannel>()
                                    .Option(ChannelOption.SoBacklog, 1024)
                                    .Handler(new LoggingHandler(LogLevel.INFO))
                                    .ChildHandler(new ActionChannelInitializer <ISocketChannel>(ch =>
                    {
                        var encoder = new StringEncoder();
                        var decoder = new StringDecoder();

                        var pipeline = ch.Pipeline;
                        switch (kind)
                        {
                        case BasedFrameDecoderKind.None:
                            break;

                        case BasedFrameDecoderKind.LengthFieldBasedFrame:
                            pipeline.AddLast(new LengthFieldPrepender(2), new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
                            break;

                        case BasedFrameDecoderKind.LineBasedFrame:
                            pipeline.AddLast(new LineBasedFrameDecoder(int.MaxValue));
                            break;

                        default:
                            break;
                        }
                        pipeline.AddLast(encoder, decoder, new ChannelHandler(this));
                    }));
                    bootstrap.BindAsync(port);
                    return(bootstrap);
                }
                catch (Exception e)
                {
                    return(null);
                }
            });

            if (_bootstrap == null)
            {
                throw new Exception("初始化Netty服务失败!");
            }
        }
Example #24
0
        public void ShouldDecodeAHuffmanEncodedStringIfLengthAndPayloadAreInMultipleBuffers()
        {
            StringDecoder Decoder = new StringDecoder(1024, bufPool);

            // Only put the prefix in the first byte
            var buf = new Buffer();

            buf.WriteByte(0xFF); // Prefix filled, non huffman, I = 127
            var consumed = Decoder.Decode(buf.View);

            Assert.False(Decoder.Done);
            Assert.Equal(1, consumed);

            // Remaining part of the length plus first content byte
            buf = new Buffer();
            buf.WriteByte(0x02); // I = 0x7F + 0x02 * 2^0 = 129 byte payload
            buf.WriteByte(0xf9); // first byte of the payload
            var expectedResult = "*";

            consumed = Decoder.DecodeCont(buf.View);
            Assert.False(Decoder.Done);
            Assert.Equal(2, consumed);

            // Half of other content bytes
            buf = new Buffer();
            for (var i = 0; i < 64; i = i + 2)
            {
                expectedResult += ")-";
                buf.WriteByte(0xfe);
                buf.WriteByte(0xd6);
            }
            consumed = Decoder.DecodeCont(buf.View);
            Assert.False(Decoder.Done);
            Assert.Equal(64, consumed);

            // Last part of content bytes
            buf = new Buffer();
            for (var i = 0; i < 64; i = i + 2)
            {
                expectedResult += "0+";
                buf.WriteByte(0x07);
                buf.WriteByte(0xfb);
            }
            consumed = Decoder.DecodeCont(buf.View);
            Assert.True(Decoder.Done);
            Assert.Equal(expectedResult, Decoder.Result);
            Assert.Equal(129, Decoder.StringLength);
            Assert.Equal(64, consumed);
        }
        public unsafe void DecoderMultipleMisalignedCallTest()
        {
            string str = "\u0135\u0136\u0137\u0138\u0139";

            var decodeBuffer = new ArraySegment<char>(new char[3]);
            StringDecoder decoder = new StringDecoder(decodeBuffer);

            byte[] bytes = Encoding.UTF8.GetBytes(str);
            decoder.Decode(new ArraySegment<byte>(bytes.Take(3).ToArray()));
            decoder.Decode(new ArraySegment<byte>(bytes.Skip(3).ToArray()));

            var decodedString = decoder.ToString();
            Console.WriteLine(decodedString);
            Assert.AreEqual(str, decodedString);
        }
Example #26
0
        public static async Task RunServerAsync()
        {
//            ServerHelper.SetConsoleLogger();

            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();

            var STRING_ENCODER = new StringEncoder();
            var STRING_DECODER = new StringDecoder();
            var SERVER_HANDLER = new TelnetServerHandler();

            X509Certificate2 tlsCertificate = null;

            if (ServerSettings.IsSsl)
            {
                tlsCertificate = new X509Certificate2(Path.Combine(KernelHelper.ProcessDirectory, "bittymud.pfx"), "password");
            }
            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (tlsCertificate != null)
                    {
                        pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                    }

                    pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(STRING_ENCODER, STRING_DECODER, SERVER_HANDLER);
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(ServerSettings.Port);

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
Example #27
0
        public void ShouldDecodeAnASCIIStringFromACompleteBuffer()
        {
            StringDecoder Decoder = new StringDecoder(1024, bufPool);

            // 0 Characters
            var buf = new Buffer();

            buf.WriteByte(0x00);
            var consumed = Decoder.Decode(buf.View);

            Assert.True(Decoder.Done);
            Assert.Equal("", Decoder.Result);
            Assert.Equal(0, Decoder.StringLength);
            Assert.Equal(1, consumed);

            buf = new Buffer();
            buf.WriteByte(0x04); // 4 Characters, non huffman
            buf.WriteByte('a');
            buf.WriteByte('s');
            buf.WriteByte('d');
            buf.WriteByte('f');

            consumed = Decoder.Decode(buf.View);
            Assert.True(Decoder.Done);
            Assert.Equal("asdf", Decoder.Result);
            Assert.Equal(4, Decoder.StringLength);
            Assert.Equal(5, consumed);

            // Multi-byte prefix
            buf = new Buffer();
            buf.WriteByte(0x7F); // Prefix filled, non huffman, I = 127
            buf.WriteByte(0xFF); // I = 0x7F + 0x7F * 2^0 = 0xFE
            buf.WriteByte(0x03); // I = 0xFE + 0x03 * 2^7 = 0xFE + 0x180 = 0x27E = 638
            var expectedLength = 638;
            var expectedString = "";

            for (var i = 0; i < expectedLength; i++)
            {
                buf.WriteByte(' ');
                expectedString += ' ';
            }
            consumed = Decoder.Decode(buf.View);
            Assert.True(Decoder.Done);
            Assert.Equal(expectedString, Decoder.Result);
            Assert.Equal(expectedLength, Decoder.StringLength);
            Assert.Equal(3 + expectedLength, consumed);
        }
Example #28
0
        private async void InitializeAsync(EndPoint endPoint, BasedFrameDecoderKind kind)
        {
            _bootstrap = await Task.Run(() =>
            {
                try
                {
                    var bootstrap = new Bootstrap()
                                    .Group(_group)
                                    .Channel <TcpSocketChannel>()
                                    .Option(ChannelOption.TcpNodelay, true)
                                    .Handler(new ActionChannelInitializer <ISocketChannel>(ch =>
                    {
                        var encoder  = new StringEncoder();
                        var decoder  = new StringDecoder();
                        var pipeline = ch.Pipeline;
                        switch (kind)
                        {
                        case BasedFrameDecoderKind.None:
                            break;

                        case BasedFrameDecoderKind.LengthFieldBasedFrame:
                            pipeline.AddLast(new LengthFieldPrepender(2), new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
                            break;

                        case BasedFrameDecoderKind.LineBasedFrame:
                            pipeline.AddLast(new LineBasedFrameDecoder(int.MaxValue));
                            break;

                        default:
                            break;
                        }
                        pipeline.AddLast(encoder, decoder, new ChannelHandler(this, false));
                    }));
                    return(bootstrap);
                }
                catch (Exception e)
                {
                }
                return(null);
            });

            if (_bootstrap == null)
            {
                throw new Exception();
            }
            DoConnect(_bootstrap, endPoint);
        }
Example #29
0
        /// <summary>
        /// Takes a list of textBoxes, try to convert each element into a double,
        /// if an element is not a double, skip it, and send the dictionary into
        /// the stringDecoder class, and return the result.
        /// </summary>
        public string EncodeDataFromTextBoxes(List <TextBox> textBoxes)
        {
            var dictionary = new Dictionary <int, double>();

            var values = textBoxes.Select(textBox => textBox.Text).ToList();

            for (int i = 0; i < values.Count; i++)
            {
                try {
                    double temperature = Convert.ToDouble(values[i]);
                    dictionary.Add(i, temperature);
                }
                catch { /* If text is not a double, ignore. */ }
            }

            return(StringDecoder.dictionaryToString(dictionary));
        } // End of TakeInfoFromTextBoxes
Example #30
0
        public void send_close_message()
        {
            var slice   = new BufferSlice(new byte[65535], 0, 65535);
            var encoder = new StringEncoder();
            var decoder = new StringDecoder();

            var sut = CreateClientChannel(slice, encoder, decoder);

            sut.MessageReceived += (channel, message) => { };
            var stream = new SslStream(new NetworkStream(_helper.Server));

            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);
            sut.Assign(_helper.Client);

            Assert.True(sut.IsConnected);

            sut.Close();

            Assert.False(sut.IsConnected);
        }
Example #31
0
        public void send_message()
        {
            var    slice    = new BufferSlice(new byte[65535], 0, 65535);
            var    encoder  = new StringEncoder();
            var    decoder  = new StringDecoder();
            object expected = null;

            var sut = CreateClientChannel(slice, encoder, decoder);

            sut.MessageReceived += (channel, message) => expected = message;
            var stream = new SslStream(new NetworkStream(_helper.Server));

            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);
            sut.Assign(_helper.Client);
            sut.Send("Hello world");

            var buf    = new byte[65535];
            var tmp    = stream.Read(buf, 0, 65535);
            var actual = Encoding.ASCII.GetString(buf, 4, tmp - 4); // string encoder have a length header.

            actual.Should().Be("Hello world");
        }
Example #32
0
        public void ShouldCheckTheMaximumStringLength()
        {
            StringDecoder Decoder = new StringDecoder(2, bufPool);

            // 2 Characters are ok
            var buf = new Buffer();

            buf.WriteByte(0x02);
            buf.WriteByte('a');
            buf.WriteByte('b');
            var consumed = Decoder.Decode(buf.View);

            Assert.True(Decoder.Done);
            Assert.Equal("ab", Decoder.Result);
            Assert.Equal(2, Decoder.StringLength);
            Assert.Equal(3, consumed);

            // 3 should fail
            buf = new Buffer();
            buf.WriteByte(0x03);
            buf.WriteByte('a');
            buf.WriteByte('b');
            buf.WriteByte('c');
            var ex = Assert.Throws <Exception>(() => Decoder.Decode(buf.View));

            Assert.Equal("Maximum string length exceeded", ex.Message);

            // Things were the length is stored in a continuation byte should also fail
            buf = new Buffer();
            buf.WriteByte(0x7F); // More than 127 bytes
            consumed = Decoder.Decode(buf.View);
            Assert.False(Decoder.Done);
            Assert.Equal(1, consumed);
            buf.WriteByte(1);
            var view = new ArraySegment <byte>(buf.Bytes, 1, 1);

            ex = Assert.Throws <Exception>(() => Decoder.DecodeCont(view));
            Assert.Equal("Maximum string length exceeded", ex.Message);
        }
Example #33
0
        public static void Main(string[] args)
        {
            try
            {
                using (var server = new NetServer())
                {
                    server.Listen((self) =>
                    {
                        System.Console.WriteLine("Server is listening on: " + self.Address.ToString());
                    });
                    server.Connect((channel) =>
                    {
                        System.Console.WriteLine("Client connected.");

                        channel.Fault((c, exception) =>
                        {
                            System.Console.WriteLine(((MiniNet.Exceptions.SocketException)exception).StatusCode.ToString());
                            System.Console.WriteLine(exception.ToString());
                        });

                        var encoding = Encoding.Unicode;
                        var decoder = new StringDecoder(encoding);
                        var encoder = new StringEncoder(encoding);

                        //channel.Authenticate();
                        channel.Start();

                        channel.Message((self, buffer) =>
                        {
                            if (buffer.Size > 0)
                            {
                                var str = decoder.Process(buffer);
                                System.Console.WriteLine(str + "-" + buffer.Size + "-");
                                System.Console.WriteLine(buffer.DumpHex(int.MaxValue));
                            }
                        });

                        /*var payload = "Server: Hello Client";
                        var message = MiniNet.Buffers.Buffer.Create(encoding.GetByteCount(payload));

                        encoder.Process(message, payload);
                        channel.SendAsync(message);*/

                        Thread.Sleep(1000);
                        //channel.Close();
                    });
                    server.Fault((exception) =>
                    {
                        System.Console.WriteLine(exception.ToString());
                    });
                    server.Bind(8080, "localhost");

                    using (var client = new TcpClient())
                    {
                        client.NoDelay = true;
                        client.Connect(server.Address.Host, server.Address.Port);
                        Thread.Sleep(100);

                        var encoding = new UnicodeEncoding(false, false, true);
                        var stream = client.GetStream();
                        //var reader = new StreamReader(stream, encoding);
                        var writer = new StreamWriter(stream, encoding) { AutoFlush = true };

                        for (int i=1; i<=4; i++)
                        {
                            /*var bytesReceived = new byte[1024];
                            var lengthReceived = client.GetStream().Read(bytesReceived, 0, bytesReceived.Length);
                            if (lengthReceived > 0)
                            {
                                var message = encoding.GetString(bytesReceived, 0, lengthReceived);
                                System.Console.WriteLine(MiniNet.Buffers.Buffer.DumpHex(bytesReceived, 0, lengthReceived, int.MaxValue));
                                System.Console.WriteLine("'" + message + "'" + lengthReceived);
                            }*/

                            writer.Write("Client: Hello Server");
                        }

                        Thread.Sleep(100);
                        System.Console.WriteLine("Press ENTER to quit");
                        System.Console.ReadLine();
                        client.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.ToString());
                System.Console.WriteLine(ex.StackTrace);
            }
        }
        public unsafe void DecodeUntilMultipleMisalignedCallTest()
        {
            string str = "\u0135\n\u0136\u0137\u0138\u0139";

            var decodeBuffer = new ArraySegment<char>(new char[3]);
            StringDecoder decoder = new StringDecoder(decodeBuffer);

            byte[] bytes = Encoding.UTF8.GetBytes(str);
            
            string result;

            var bytesLeftOver = new ArraySegment<byte>(bytes.Take(4).ToArray());

            Assert.IsTrue(decoder.DecodeAndSplitAtUtf8Character(bytesLeftOver, '\n', out result, out bytesLeftOver));
            Assert.AreEqual("\u0135", result);
            Assert.AreEqual(1, bytesLeftOver.Count);

            Assert.IsFalse(decoder.DecodeAndSplitAtUtf8Character(bytesLeftOver, '\n', out result, out bytesLeftOver));
            Assert.IsNull(result);
            Assert.AreEqual(0, bytesLeftOver.Count);
        }