• 学习了半个多月的TankGame


    public class Server {
        public static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    
        public void serverStart() {
            /** 负责处理连接的 group 一般只需要一个线程 */
            EventLoopGroup bossGroup = new NioEventLoopGroup(1);
            /** 负责发送与接收消息的 group 具体几个现场看情况 */
            EventLoopGroup workerGroup = new NioEventLoopGroup(2);
    
            try {
                ServerBootstrap b = new ServerBootstrap();
                ChannelFuture f = b.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ch.pipeline()
                                .addLast(new MsgEncode())
                                .addLast(new MsgDecode())
                                .addLast(new ServerChildHandler());
                            }
                        })
                        .bind(8888)
                        .sync();
    
                ServerFrame.INSTANCE.updateServerMsg("server started!");
    
                f.channel().closeFuture().sync(); //close()->ChannelFuture
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                workerGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            }
        }
    
    
    }
    
    class ServerChildHandler extends ChannelInboundHandlerAdapter { //SimpleChannleInboundHandler Codec
    
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            Server.clients.add(ctx.channel());
        }
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println(msg);
            ServerFrame.INSTANCE.updateClientMsg(msg.toString());
            Server.clients.writeAndFlush(msg);
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            Server.clients.remove(ctx.channel());
            ctx.close();
        }
    
    
    }

    client

    public class Client {
        public static final Client INSTANCE = new Client();
        private Channel channel = null;
    
        private Client() {}
        public void connect() {
            EventLoopGroup group = new NioEventLoopGroup(1);
            Bootstrap b = new Bootstrap();
            try {
                ChannelFuture f = b.group(group).channel(NioSocketChannel.class).handler(new ClientChannelInitializer())
                        .connect("localhost", 8888);
                f.addListener((ChannelFuture future)-> {
                    if (!future.isSuccess()) {
                        System.out.println("not connected!");
                    } else {
                        System.out.println("connected!");
                        // initialize the channel
                        channel = future.channel();
                    }
                });
                f.sync();
                // wait until close
                f.channel().closeFuture().sync();
                System.out.println("connection closed!");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                group.shutdownGracefully();
            }
        }
        public void send(Msg msg) {
            channel.writeAndFlush(msg);
        }
    }
    
    class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {
    
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline()
                    .addLast(new MsgEncode())
                    .addLast(new MsgDecode())
                    .addLast(new ClientHandler());
        }
    
    }
    
    class ClientHandler extends SimpleChannelInboundHandler<Msg> {
    
        @Override
        public void channelRead0(ChannelHandlerContext ctx, Msg msg) throws Exception {
           msg.handle();
        }
    
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            TankJoinMsg tankJoinMsg = new TankJoinMsg(GameModel.getInstance().getMainTank());
            System.out.println("发送消息到服务器 : "+tankJoinMsg);
            ctx.writeAndFlush(tankJoinMsg);
        }
    
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            super.userEventTriggered(ctx, evt);
            //如果消息是心跳包
            if(evt instanceof IdleStateEvent){
        
            }
        }
    }
  • 相关阅读:
    angularjs中的页面访问权限设置
    Html页面head标签元素的意义和应用场景
    脚本引用中的defer和async的用法和区别
    自适应页面中如何使用雪碧图
    网页颜色分辨测试小游戏的js化辨别及优化
    jQuery1.9及其以上版本中动态元素on绑定事件无效解决方案
    Data URL简介及Data URL的利弊
    浏览器调试:事件定位与源码查找
    简述ES5 ES6
    移动端中pagehide、pageshow的应用
  • 原文地址:https://www.cnblogs.com/self-crossing/p/11011703.html
Copyright © 2020-2023  润新知