Beispiel #1
0
 public MapInstance(Map.Map map, Guid guid, bool shopAllowed, MapInstanceType type,
                    IMapItemGenerationService mapItemGenerationService, ILogger logger)
 {
     LastPackets     = new ConcurrentQueue <IPacket>();
     XpRate          = 1;
     DropRate        = 1;
     ShopAllowed     = shopAllowed;
     MapInstanceType = type;
     Map             = map;
     MapInstanceId   = guid;
     Portals         = new List <Portal>();
     _monsters       = new ConcurrentDictionary <int, MapMonster>();
     _npcs           = new ConcurrentDictionary <int, MapNpc>();
     MapItems        = new ConcurrentDictionary <long, MapItem>();
     _isSleeping     = true;
     LastUnregister  = SystemTime.Now().AddMinutes(-1);
     ExecutionEnvironment.TryGetCurrentExecutor(out var executor);
     Sessions = new DefaultChannelGroup(executor);
     _mapItemGenerationService = mapItemGenerationService;
     _logger  = logger;
     Requests = new Dictionary <Type, Subject <RequestData <MapInstance> > >
     {
         [typeof(IMapInstanceEntranceEventHandler)] = new Subject <RequestData <MapInstance> >()
     };
 }
        public override void ChannelActive(IChannelHandlerContext ctx)
        {
            IChannelGroup g = Group;

            if (g == null)
            {
                lock (this)
                {
                    if (Group == null)
                    {
                        Group = g = new DefaultChannelGroup(ctx.Executor);
                    }
                }
            }

            // Detect when client disconnects
            ctx.Channel.CloseCompletion.ContinueWith((x) =>
            {
                Logger.Warn("Channel Closed");
                g?.Remove(ctx.Channel);
                OnChannelInactive?.Invoke(ctx.Channel);
            });

            // Add to channels list
            g.Add(ctx.Channel);

            // Send event upstream
            OnChannelActive?.Invoke(ctx.Channel);
        }
Beispiel #3
0
 public MapInstance(Map.Map map, Guid guid, bool shopAllowed, MapInstanceType type,
                    IMapItemProvider mapItemProvider, ILogger logger, List <IMapInstanceEventHandler> mapInstanceEventHandler)
 {
     LastPackets     = new ConcurrentQueue <IPacket>();
     XpRate          = 1;
     DropRate        = 1;
     ShopAllowed     = shopAllowed;
     MapInstanceType = type;
     Map             = map;
     MapInstanceId   = guid;
     Portals         = new List <Portal>();
     _monsters       = new ConcurrentDictionary <int, MapMonster>();
     _npcs           = new ConcurrentDictionary <int, MapNpc>();
     MapItems        = new ConcurrentDictionary <long, MapItem>();
     _isSleeping     = true;
     LastUnregister  = SystemTime.Now().AddMinutes(-1);
     ExecutionEnvironment.TryGetCurrentExecutor(out var executor);
     Sessions                 = new DefaultChannelGroup(executor);
     _mapItemProvider         = mapItemProvider;
     _logger                  = logger;
     Requests                 = new Dictionary <MapInstanceEventType, Subject <RequestData <MapInstance> > >();
     _mapInstanceEventHandler = mapInstanceEventHandler;
     foreach (var eventTypes in Enum.GetValues(typeof(MapInstanceEventType)))
     {
         Requests[(MapInstanceEventType)eventTypes !] = new Subject <RequestData <MapInstance> >();
Beispiel #4
0
        public override void ChannelActive(IChannelHandlerContext contex)
        {
            IChannelGroup g = Group;

            if (g == null)
            {
                lock (this)
                {
                    g = Group ?? (Group = new DefaultChannelGroup(contex.Executor));
                }
            }
            base.ChannelActive(contex);
            string msg = $"欢迎 to {0} secure chat server! { Dns.GetHostName()}\n";

            ReplyContent <string> reply = new ReplyContent <string>()
            {
                ConnectionId = $"{contex.Channel.Id}",
                Cmd          = 0,
                Scope        = 0,
                Message      = msg
            };

            contex.WriteAndFlushAsync(reply.ToString());
            g.Add(contex.Channel);
        }
Beispiel #5
0
 public Group(GroupType type)
 {
     Type    = type;
     GroupId = -1;
     ExecutionEnvironment.TryGetCurrentExecutor(out var executor);
     Sessions = new DefaultChannelGroup(executor);
 }
Beispiel #6
0
        public async Task TestBindMultiple()
        {
            DefaultChannelGroup channelGroup = new DefaultChannelGroup();
            IEventLoopGroup     group        = new MultithreadEventLoopGroup(1);

            try
            {
                for (int i = 0; i < 100; i++)
                {
                    Bootstrap udpBootstrap = new Bootstrap();
                    udpBootstrap
                    .Group(group)
                    .Channel <SocketDatagramChannel>()
                    .Option(ChannelOption.SoBroadcast, true)
                    .Handler(new ChannelInboundHandlerAdapter0());
                    var datagramChannel = await udpBootstrap
                                          .BindAsync(new IPEndPoint(IPAddress.Loopback, 0));

                    channelGroup.Add(datagramChannel);
                }
                Assert.Equal(100, channelGroup.Count);
            }
            finally
            {
                await channelGroup.CloseAsync();

                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
Beispiel #7
0
        public async Task TestNotThrowBlockingOperationException()
        {
            IEventLoopGroup bossGroup   = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup(1);

            IChannelGroup allChannels = new DefaultChannelGroup();

            ServerBootstrap b = new ServerBootstrap();

            b.Group(bossGroup, workerGroup);
            b.ChildHandler(new ChannelInboundHandlerAdapter0(allChannels));
            b.Channel <TcpServerSocketChannel>();

            var ch = await b.BindAsync(0);

            allChannels.Add(ch);
            await allChannels.CloseAsync();

            await Task.WhenAll(
                bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)),
                workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5))
                );

            await bossGroup.TerminationCompletion;
            await workerGroup.TerminationCompletion;
        }
Beispiel #8
0
 public Group(GroupType type)
 {
     LastPackets = new ConcurrentQueue <IPacket>();
     Type        = type;
     GroupId     = -1;
     ExecutionEnvironment.TryGetCurrentExecutor(out var executor);
     Sessions = new DefaultChannelGroup(executor);
 }
Beispiel #9
0
        //---------------------------------------------------------------------
        public void addSession(IChannelHandlerContext c)
        {
            IChannelGroup g = ChannelGroup;

            if (g == null)
            {
                lock (this)
                {
                    if (ChannelGroup == null)
                    {
                        g = ChannelGroup = new DefaultChannelGroup(c.Executor);
                    }
                }
            }

            ChannelGroup.Add(c.Channel);
        }
        public override void ChannelActive(IChannelHandlerContext contex)
        {
            IChannelGroup g = Group;

            if (g == null)
            {
                lock (this)
                {
                    if (Group == null)
                    {
                        g = Group = new DefaultChannelGroup(contex.Executor);
                    }
                }
            }
            this.OnChannelActive(this, contex);
            contex.WriteAndFlushAsync(string.Format("欢迎 to {0} secure chat server!\n", Dns.GetHostName()));
            g.Add(contex.Channel);
        }
Beispiel #11
0
 public MapInstance(Map.Map map, Guid guid, bool shopAllowed, MapInstanceType type,
                    List <NpcMonsterDto> npcMonsters)
 {
     _npcMonsters    = npcMonsters;
     XpRate          = 1;
     DropRate        = 1;
     ShopAllowed     = shopAllowed;
     MapInstanceType = type;
     Map             = map;
     MapInstanceId   = guid;
     Portals         = new List <Portal>();
     _monsters       = new ConcurrentDictionary <long, MapMonster>();
     _npcs           = new ConcurrentDictionary <long, MapNpc>();
     DroppedList     = new ConcurrentDictionary <long, MapItem>();
     _isSleeping     = true;
     LastUnregister  = DateTime.Now.AddMinutes(-1);
     ExecutionEnvironment.TryGetCurrentExecutor(out var executor);
     Sessions = new DefaultChannelGroup(executor);
 }
Beispiel #12
0
        //private static volatile IChannelGroup group;
        public override void ChannelActive(IChannelHandlerContext contex)
        {
            IAttribute <string>        der       = contex.GetAttribute(AttributeMapConstant.HttpAttriKey);
            IAttribute <IChannelGroup> parentAtt = contex.Channel.Parent.GetAttribute(AttributeMapConstant.SockerGroup);
            IChannelGroup g = parentAtt.Get();

            if (g == null)
            {
                lock (this)
                {
                    if (g == null)
                    {
                        var chennGroup = new DefaultChannelGroup(contex.Executor);
                        g = chennGroup;
                        parentAtt.SetIfAbsent(chennGroup);
                    }
                }
            }
            contex.WriteAndFlushAsync(string.Format("Welcome to {0} secure chat server!{1}", Dns.GetHostName(), delimiterStr));
            g.Add(contex.Channel);
        }
Beispiel #13
0
 public MapInstance(Map.Map map, Guid guid, bool shopAllowed, MapInstanceType type,
                    IMapItemProvider mapItemProvider, IAdapter adapter, ILogger logger)
 {
     XpRate          = 1;
     DropRate        = 1;
     ShopAllowed     = shopAllowed;
     MapInstanceType = type;
     Map             = map;
     MapInstanceId   = guid;
     Portals         = new List <Portal>();
     _monsters       = new ConcurrentDictionary <int, MapMonster>();
     _npcs           = new ConcurrentDictionary <int, MapNpc>();
     MapItems        = new ConcurrentDictionary <long, MapItem>();
     _isSleeping     = true;
     LastUnregister  = SystemTime.Now().AddMinutes(-1);
     ExecutionEnvironment.TryGetCurrentExecutor(out var executor);
     Sessions         = new DefaultChannelGroup(executor);
     _mapItemProvider = mapItemProvider;
     _adapter         = adapter;
     _logger          = logger;
 }
Beispiel #14
0
 private Broadcaster()
 {
     ExecutionEnvironment.TryGetCurrentExecutor(out var executor);
     Sessions = new DefaultChannelGroup(executor);
 }
Beispiel #15
0
        static async Task RunClientAsync()
        {
            var builder = new UriBuilder
            {
                Scheme = "ws",
                Host   = "127.0.0.1",
                Port   = 18089
            };

            string path = "websocket";

            if (!string.IsNullOrEmpty(path))
            {
                builder.Path = path;
            }

            Uri uri = builder.Uri;
            //ExampleHelper.SetConsoleLogger();
            IEventLoopGroup group = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Option(ChannelOption.TcpNodelay, true);

                bootstrap.Channel <TcpSocketChannel>();

                // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
                // If you change it to V00, ping is not supported and remember to change
                // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
                var handShaker = WebSocketClientHandshakerFactory.NewHandshaker(
                    uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders());
                var channelGroup = new DefaultChannelGroup(null);

                bootstrap.Handler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast(
                        new HttpClientCodec(),
                        new HttpObjectAggregator(8192),
                        //WebSocketClientCompressionHandler.Instance,
                        new WebSocketClientProtocolHandler(handShaker, true),
                        new BinaryWebSocketFrameHandler(),
                        new ProtocolDecoder(),
                        new ProtocolEncoder(),
                        new MessageHandler(channelGroup));

                    pipeline.AddLast(new ProtocolEncoder());
                }));

                IChannel ch = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 18089));

                Console.WriteLine("WebSocket handshake completed.\n");
                Console.WriteLine("\t[bye]:Quit \n\t [ping]:Send ping frame\n\t Enter any text and Enter: Send text frame");
                while (true)
                {
                    string msg = Console.ReadLine();
                    if (msg == null)
                    {
                        break;
                    }
                    else if ("bye".Equals(msg.ToLower()))
                    {
                        await ch.WriteAndFlushAsync(new CloseWebSocketFrame());

                        break;
                    }
                    else if ("ping".Equals(msg.ToLower()))
                    {
                        var frame = new PingWebSocketFrame(Unpooled.WrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                        await ch.WriteAndFlushAsync(frame);
                    }
                    else
                    {
                        //WebSocketFrame frame = new TextWebSocketFrame(msg);
                        //await ch.WriteAndFlushAsync(frame);

                        var req = new LoginValidateRequest
                        {
                            Account = "sp001",
                            Passwd  = "111",
                            ZoneId  = 4
                        };
                        await ch.WriteAndFlushAsync(req);
                    }
                }

                await ch.CloseAsync();
            }
            finally
            {
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }