netty 聊天版

實現以下功能:

  • 1,一個客戶端上線/下線,通知所有的用戶。

  • 2,一個客戶端發送消息,廣播所有的客戶端。

server端代碼

  • 1,Server.java
public class Server {

    public static void main(String... arg) throws Exception {

        //負責接收客戶端連接
        NioEventLoopGroup boss = new NioEventLoopGroup();

        //負責處理客戶端連接
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();


        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ServerChatinitlizer());

            //綁定端口號
            ChannelFuture channelFuture = bootstrap.bind(8899).sync();
            channelFuture.channel().closeFuture().sync();

        } finally {
            boss.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}

  • 2,ServerChatinitlizer.java
public class ServerChatinitlizer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        //編碼解碼器

        // 換行分割解碼器 \r\n
        pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));

        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));

        //自己的處理器
        pipeline.addLast(new ServerChatHandler());


    }
}

  • 3,ServerChatHandler.java
/**
 * 客戶端上線/下線 提示所有的人
 * 發送消息發給所有的人
 */
public class ServerChatHandler extends SimpleChannelInboundHandler<String> {

    //保存已建立所用用戶的實例
    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 (ch == channel) {  //表示自己
                channel.writeAndFlush("[自己]  "  + msg + "\n");
            } else {
                ch.writeAndFlush(ch.remoteAddress() + "  發送的消息  " + msg + "\n");
            }
        });

    }

    //客戶端與服務器端建立好連接
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerAdded");
        Channel channel = ctx.channel();
        //廣播已連接的客戶端 有新的用戶上線
        channelGroup.writeAndFlush("[服務器]-" + channel.remoteAddress() +" 上線\n");
        // 保存用戶實例
        channelGroup.add(channel);

    }

    //鏈接斷開
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

        System.out.println("handlerRemoved");
        Channel channel = ctx.channel();
        //廣播已連接的客戶端 用戶下線
        channelGroup.writeAndFlush("[服務器]-" + channel.remoteAddress() + " 下線\n");

        //channelGroup 會自動 剔除已斷開的用戶連接

    }


    //處于活動狀態
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("[服務器]-" + channel.remoteAddress() +" 上線\n");
    }


    //下線
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Channel channel = ctx.channel();
        System.out.println("[服務器]-" + channel.remoteAddress() +  " 下線\n");
    }


    // 發生異常關閉連接
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}


client端代碼

  • 1,Client.java
public class Client {
    public static void main(String... arg) throws Exception {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try {

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .handler(new ChatInitializer());

           Channel channel = bootstrap.connect("127.0.0.1",8899).sync().channel();

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            while (true){
                channel.writeAndFlush(br.readLine()+"\r\n");
            }

        } finally {
            eventLoopGroup.shutdownGracefully();
        }

    }
}

  • 2, ChatInitializer.java
public class ChatInitializer 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 StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));

        pipeline.addLast(new ChatHandler());

    }
}

  • 3, ChatHandler
public class ChatHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        System.out.println(" 接收到數據 " + msg);

    }
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,886評論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,132評論 25 708
  • 2016-02-01 13:10:403 <1>在中世紀,一小時等于四百八十盎司細沙,想知道自己倒轉了多少次沙漏,...
    blair_c閱讀 301評論 0 0
  • 今天偶然間從文章中看到格局一詞,不由的會心一笑。好久沒看到這個詞了,記得當初看到的時候還特意去百度了一下格局這...
    小梔子花閱讀 1,258評論 4 2
  • 漆黑的夜, 高筑的圍墻 墻外,絢爛的綻放 墻內,深海的冰涼 透過層層的高墻 我隱約看見 那耀眼般的存在 我伸出手 ...
    不灬良人閱讀 203評論 2 4