Пример #1
0
        static void Main(string[] args)
        {
            IoAcceptor acceptor = new AsyncSocketAcceptor();

            acceptor.FilterChain.AddLast("logger", new LoggingFilter());
            acceptor.FilterChain.AddLast("codec", new ProtocolCodecFilter(
                new TextLineCodecFactory(Encoding.UTF8)));

            acceptor.ExceptionCaught += (s, e) => e.Session.Close(true);
            acceptor.MessageReceived += (s, e) =>
            {
                String str = e.Message.ToString();
                StringBuilder sb = new StringBuilder(str.Length);
                for (int i = str.Length - 1; i >= 0; i--)
                {
                    sb.Append(str[i]);
                }
                e.Session.Write(sb.ToString());
            };

            acceptor.Bind(new IPEndPoint(IPAddress.Any, port));

            Console.WriteLine("Listening on " + acceptor.LocalEndPoint);
            Console.ReadLine();
        }
Пример #2
0
        public bool StartUp(ServerConfig config = null, params Autofac.Module[] modules)
        {
            var setupOk = ObjectHost.Setup(
                new Module[] 
                { 
                    new RpcNetModule(),
                    new ServerModule()
                }.Concat(modules));

            if (setupOk)
            {
                using(var scope = ObjectHost.Host.BeginLifetimeScope())
                {
                    config = config ?? new ServerConfig();
                    acceptor = new AsyncSocketAcceptor(config.MaxConnections);
                    acceptor.FilterChain.AddLast("session-metrics", new SessionMetricsFilter());
                    acceptor.FilterChain.AddLast("logger", new LoggingFilter());
                    acceptor.FilterChain.AddLast("codec",
                        new ProtocolCodecFilter(new MessageCodecFactory()));
                    filterTypes.ForEach(type => filters.Add(scope.Resolve(type) as AbstractFilter));
                    filters.ForEach(filter => acceptor.FilterChain.AddLast(filter.Name, filter));
                    acceptor.FilterChain.AddLast("exceptionCounter", scope.Resolve<ExceptionCounterFilter>());
                    acceptor.FilterChain.AddLast("session-abnormal", scope.Resolve<SessionAbnormalFilter>());
                    acceptor.Handler = scope.Resolve<CommandHandler>();
                    acceptor.SessionConfig.ReadBufferSize = config.ReadBufferSize;
                    acceptor.SessionConfig.SendBufferSize = config.SendBufferSize;
                    acceptor.SessionConfig.ReaderIdleTime = config.ReaderIdleTime;
                    acceptor.SessionConfig.WriterIdleTime = config.WriterIdleTime;
                    acceptor.SessionConfig.WriteTimeout = config.WriteTimeout;
                    acceptor.SessionConfig.KeepAlive = config.KeepAlive;
                    acceptor.Bind(EndPoint);
                }
            }
            return setupOk;
        }   
Пример #3
0
        /// <summary>
        /// 初始化Socket服务
        /// </summary>
        private void InitializeSocketService()
        {
            var acceptor = new AsyncSocketAcceptor();
            acceptor.SessionConfig.ReadBufferSize = 2048;
            acceptor.SessionConfig.SetIdleTime(IdleStatus.BothIdle, 10);

            // 添加过滤器
            var demuxingCodec = new DemuxingProtocolCodecFactory();
            demuxingCodec.AddMessageEncoder<ITransferingZipFile, TransferingZipFileProtocolEncoder>();
            demuxingCodec.AddMessageEncoder<IUpdateFileCollection, UpdateFileCollectionProtocolEncoder>();
            demuxingCodec.AddMessageDecoder<ClientInfoProtocolDecoder>();
            demuxingCodec.AddMessageDecoder<FileHashesProtocolDecoder>();
            acceptor.FilterChain.AddLast("codec", new ProtocolCodecFilter(demuxingCodec));
            acceptor.FilterChain.AddLast("logger", new LoggingFilter());

            // 添加业务逻辑
            var demuxingHandler = new DemuxingIoHandler();
            demuxingHandler.AddReceivedMessageHandler(new ClientInfoMessageHandler((s, o) =>
            {
                // TODO 服务器收到客户端发来的客户端信息后,校验MachineID,AppBranchID,
                // Serial,Expiration等信息(见数据库,见AppUpdateServer.Models.ClientInfo类),
                // 将更新文件名列表发给客户端
            }));
            demuxingHandler.AddReceivedMessageHandler(new FileHashesMessageHandler((s, o) =>
            {
                // TODO 服务器收到客户端发来的文件Hash后,在服务器端对比Hash,并将Hash不同的文件打包成压缩包发送给客户端
            }));
            acceptor.Handler = demuxingHandler;

            Container.RegisterInstance<IoAcceptor>(acceptor, new ContainerControlledLifetimeManager());
        }
Пример #4
0
        private static void StartServer()
        {
            AsyncSocketAcceptor acceptor = new AsyncSocketAcceptor();

            DefaultIoFilterChainBuilder filters = acceptor.FilterChain;

            // Inject the SSL filter

            SslFilter sslFilter = new SslFilter(AppDomain.CurrentDomain.BaseDirectory + "\\TempCert.cer");
            filters.AddLast("sslFilter", sslFilter);

            // Inject the TestLine codec filter
            filters.AddLast("text", new ProtocolCodecFilter(new TextLineCodecFactory()));

            acceptor.MessageReceived += (s, e) =>
            {
                String line = (String)e.Message;

                if (line.StartsWith("hello"))
                {
                    Debug.WriteLine("Server got: 'hello', waiting for 'send'");
                    Thread.Sleep(1500);
                }
                else if (line.StartsWith("send"))
                {
                    Debug.WriteLine("Server got: 'send', sending 'data'");
                    e.Session.Write("data");
                }
            };

            acceptor.Bind(new IPEndPoint(IPAddress.Any, port));
        }
Пример #5
0
 public void SetUp()
 {
     acceptor = new AsyncSocketAcceptor();
     IKeepAliveMessageFactory factory = new ServerFactory();
     KeepAliveFilter filter = new KeepAliveFilter(factory, IdleStatus.BothIdle);
     acceptor.FilterChain.AddLast("keep-alive", filter);
     acceptor.DefaultLocalEndPoint = new IPEndPoint(IPAddress.Loopback, 0);
     acceptor.Bind();
     port = ((IPEndPoint)acceptor.LocalEndPoint).Port;
 }
Пример #6
0
        static void Main(string[] args)
        {
            IoAcceptor acceptor = new AsyncSocketAcceptor();

            if (ssl)
            {
                acceptor.FilterChain.AddLast("ssl", new SslFilter(AppDomain.CurrentDomain.BaseDirectory + "\\TempCert.cer"));
                Console.WriteLine("SSL ON");
            }

            acceptor.FilterChain.AddLast("logger", new LoggingFilter());
            acceptor.FilterChain.AddLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory()));

            acceptor.Handler = new ChatProtocolHandler();

            acceptor.Bind(new IPEndPoint(IPAddress.Any, port));

            Console.WriteLine("Listening on " + acceptor.LocalEndPoint);

            Console.ReadLine();
        }
Пример #7
0
        /// <summary>
        /// The server implementation. It's based on TCP, and uses a logging filter 
        /// plus a text line decoder.
        /// </summary>
        static void Main(string[] args)
        {
            // Create the acceptor
            IoAcceptor acceptor = new AsyncSocketAcceptor();

            // Add two filters : a logger and a codec
            acceptor.FilterChain.AddLast("logger", new LoggingFilter());
            acceptor.FilterChain.AddLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Encoding.UTF8)));

            // Attach the business logic to the server
            acceptor.Handler = new TimeServerHandler();

            // Configurate the buffer size and the iddle time
            acceptor.SessionConfig.ReadBufferSize = 2048;
            acceptor.SessionConfig.SetIdleTime(IdleStatus.BothIdle, 10);

            // And bind !
            acceptor.Bind(new IPEndPoint(IPAddress.Any, port));

            Console.ReadLine();
        }
Пример #8
0
        static void Main(string[] args)
        {
            /*
             * ReuseBuffer needs to be false since we have a ExecutorFilter before
             * ProtocolCodecFilter which processes incoming IoBuffer.
             */
            IoAcceptor acceptor = new AsyncSocketAcceptor() { ReuseBuffer = false };

            acceptor.FilterChain.AddLast("logger", new LoggingFilter());
            acceptor.FilterChain.AddLast("executor", new ExecutorFilter());
            acceptor.FilterChain.AddLast("to-string", new ProtocolCodecFilter(
                new TextLineCodecFactory(Encoding.UTF8)));
            acceptor.FilterChain.AddLast("to-haiki", new ToHaikuIoFilter());

            acceptor.ExceptionCaught += (s, e) => e.Session.Close(true);

            HaikuValidator validator = new HaikuValidator();
            acceptor.MessageReceived += (s, e) =>
            {
                Haiku haiku = (Haiku)e.Message;

                try
                {
                    validator.Validate(haiku);
                    e.Session.Write("HAIKU!");
                }
                catch (InvalidHaikuException ex)
                {
                    e.Session.Write("NOT A HAIKU: " + ex.Message);
                }
            };

            acceptor.Bind(new IPEndPoint(IPAddress.Any, port));

            Console.WriteLine("Listening on " + acceptor.LocalEndPoint);
            Console.ReadLine();
        }
Пример #9
0
        static void Main(string[] args)
        {
            IoAcceptor acceptor = new AsyncSocketAcceptor();

            if (ssl)
                acceptor.FilterChain.AddLast("ssl", new SslFilter(AppDomain.CurrentDomain.BaseDirectory + "\\TempCert.cer"));

            acceptor.FilterChain.AddLast("logger", new LoggingFilter());

            acceptor.Activated += (s, e) => Console.WriteLine("ACTIVATED");
            acceptor.Deactivated += (s, e) => Console.WriteLine("DEACTIVATED");
            acceptor.SessionCreated += (s, e) => e.Session.Config.SetIdleTime(IdleStatus.BothIdle, 10);
            acceptor.SessionOpened += (s, e) => Console.WriteLine("OPENED");
            acceptor.SessionClosed += (s, e) => Console.WriteLine("CLOSED");
            acceptor.SessionIdle += (s, e) => Console.WriteLine("*** IDLE #" + e.Session.GetIdleCount(IdleStatus.BothIdle) + " ***");
            acceptor.ExceptionCaught += (s, e) => e.Session.Close(true);
            acceptor.MessageReceived += (s, e) =>
            {
                Console.WriteLine("Received : " + e.Message);
                IoBuffer income = (IoBuffer)e.Message;
                IoBuffer outcome = IoBuffer.Allocate(income.Remaining);
                outcome.Put(income);
                outcome.Flip();
                e.Session.Write(outcome);
            };

            acceptor.Bind(new IPEndPoint(IPAddress.Any, port));

            Console.WriteLine("Listening on " + acceptor.LocalEndPoint);

            while (true)
            {
                Console.WriteLine("R: " + acceptor.Statistics.ReadBytesThroughput +
                    ", W: " + acceptor.Statistics.WrittenBytesThroughput);
                Thread.Sleep(3000);
            }
        }
Пример #10
0
        static void Main(string[] args)
        {
            AsyncSocketAcceptor acceptor = new AsyncSocketAcceptor();

            if (USE_CUSTOM_CODEC)
            {
                acceptor.FilterChain.AddLast("codec",
                    new ProtocolCodecFilter(new SumUpProtocolCodecFactory(true)));
            }
            else
            {
                acceptor.FilterChain.AddLast("codec",
                    new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
            }

            acceptor.FilterChain.AddLast("logger", new LoggingFilter());

            acceptor.SessionOpened += (s, e) =>
            {
                e.Session.Config.SetIdleTime(IdleStatus.BothIdle, 60);
                e.Session.SetAttribute(SUM_KEY, 0);
            };

            acceptor.SessionIdle += (s, e) =>
            {
                e.Session.Close(true);
            };

            acceptor.ExceptionCaught += (s, e) =>
            {
                Console.WriteLine(e.Exception);
                e.Session.Close(true);
            };

            acceptor.MessageReceived += (s, e) =>
            {
                // client only sends AddMessage. otherwise, we will have to identify
                // its type using instanceof operator.
                AddMessage am = (AddMessage)e.Message;

                // add the value to the current sum.
                Int32 sum = e.Session.GetAttribute<Int32>(SUM_KEY);
                Int32 value = am.Value;
                Int64 expectedSum = (Int64)sum + value;
                if (expectedSum > Int32.MaxValue || expectedSum < Int32.MinValue)
                {
                    // if the sum overflows or underflows, return error message
                    ResultMessage rm = new ResultMessage();
                    rm.Sequence = am.Sequence; // copy sequence
                    rm.OK = false;
                    e.Session.Write(rm);
                }
                else
                {
                    // sum up
                    sum = (int)expectedSum;
                    e.Session.SetAttribute(SUM_KEY, sum);

                    // return the result message
                    ResultMessage rm = new ResultMessage();
                    rm.Sequence = am.Sequence; // copy sequence
                    rm.OK = true;
                    rm.Value = sum;
                    e.Session.Write(rm);
                }
            };

            acceptor.Bind(new IPEndPoint(IPAddress.Any, SERVER_PORT));

            Console.WriteLine("Listening on port " + SERVER_PORT);
            Console.ReadLine();
        }