美文网首页
3.简易聊天室

3.简易聊天室

作者: 八颗小牙坏脾气 | 来源:发表于2018-12-13 23:49 被阅读0次

    服务端

    ublic class MyChatServer {
    
        public static final int INET_PORT = 8888;
        public static void main(String[] args) throws Exception {
            EventLoopGroup boss = new NioEventLoopGroup();
            EventLoopGroup worker = new NioEventLoopGroup();
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            try {
                serverBootstrap.group(boss, worker)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new MyChatServerInitializer());
                ChannelFuture future = serverBootstrap.bind(INET_PORT).sync();
                future.channel().closeFuture().sync();
            } finally {
                boss.shutdownGracefully();
                worker.shutdownGracefully();
            }
        }
    }
    
    public class MyChatServerInitializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
            pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
            pipeline.addLast(new MyChatServerHandler());
        }
    }
    
    public class MyChatServerHandler extends SimpleChannelInboundHandler<String> {
    
        public static final String STRING = "\n";
        public static final String SEND_MSG = "发送的消息:";
        public static final String ITSELF = "【自己】";
        public static final String JOIN = "加入";
        public static final String LEFT = "离开";
        public static final String ON_LINE = " 上线";
        public static final String OFF_LINE = " 下线";
        public static final String SERVER = "【服务器】 - ";
        private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            Channel channel = ctx.channel();
            channelGroup.forEach(ch -> {
                if (channel != ch) {
                    ch.writeAndFlush(channel.remoteAddress() + SEND_MSG + msg + "\n");
                } else {
                    ch.writeAndFlush(ITSELF + msg + "\n");
                }
            });
        }
    
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            Channel channel = ctx.channel();
            channelGroup.writeAndFlush(SERVER + channel.remoteAddress() + JOIN + "\n");
            channelGroup.add(channel);
        }
    
        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            Channel channel = ctx.channel();
            channelGroup.writeAndFlush(SERVER + channel.remoteAddress() + LEFT + STRING);
    //        channelGroup.remove(channel); 不用显示调用
        }
    
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            Channel channel = ctx.channel();
            System.out.println(channel.remoteAddress() + ON_LINE + STRING);
        }
    
        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            Channel channel = ctx.channel();
            System.out.println(channel.remoteAddress() + OFF_LINE + STRING);
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }
    

    客户端

    public class MyChatClient {
        public static void main(String[] args) throws Exception{
            EventLoopGroup group = new NioEventLoopGroup();
            Bootstrap bootstrap = new Bootstrap();
            try {
                bootstrap.group(group)
                        .channel(NioSocketChannel.class)
                        .handler(new MyChatClientInitializer());
                Channel channel = bootstrap.connect("localhost", 8888).sync().channel();
    
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
                for (; ; ) {
                    channel.writeAndFlush(br.readLine() + "\r\n");
                }
    
            } finally {
                group.shutdownGracefully();
            }
        }
    }
    
    public class MyChatClientInitializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
            pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
            pipeline.addLast(new MyChatClientlHandler());
        }
    }
    
    public class MyChatClientlHandler extends SimpleChannelInboundHandler<String> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            System.out.println(msg);
        }
    }
    

    相关文章

      网友评论

          本文标题:3.简易聊天室

          本文链接:https://www.haomeiwen.com/subject/szwihqtx.html