1. 程式人生 > 其它 >Netty簡易聊天室

Netty簡易聊天室

技術標籤:Javanetty

Netty入門 : 實現簡易聊天室

  1. 準備工作: 新增依賴包(JDK版本 8 以上)
 	<dependency>
       <groupId>io.netty</groupId>
       <artifactId>netty-all</artifactId>
       <version>4.1.55.Final</version>
    </dependency>
  1. server端程式碼
 package netty;

import io.netty.bootstrap.
ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.
netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import java.util.Scanner; public class NettyServer { public static void main(String[] args) throws InterruptedException {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1); NioEventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG,1024).childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("decoder",new StringDecoder()); pipeline.addLast("encoder",new StringEncoder()); pipeline.addLast(new NettyServerHandler()); } }); System.out.println("Netty server start ..."); ChannelFuture cf = bootstrap.bind(9000).sync(); cf.addListener(cd->{ if(cd.isSuccess()){ System.out.println("success"); }else{ System.out.println("failed"); } }); Scanner scanner = new Scanner(System.in); // 服務端給客戶端發信息 while (scanner.hasNextLine()){ String msg = scanner.nextLine(); NettyServerHandler.sendAll(msg); //cf.channel().writeAndFlush(msg); } cf.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
  1. 客戶端程式碼
package netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("decoder",new StringDecoder());
                            pipeline.addLast("encoder",new StringEncoder());
                            pipeline.addLast(new NettyClientHandler());
                        }
                    });
            System.out.println( " netty client start ");
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",9000).sync();
            Channel channel = channelFuture.channel();
            System.out.println( "======"+channel.localAddress()+"======");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()){
                String msg = scanner.nextLine();
                channel.writeAndFlush(msg);
            }

           channelFuture.channel().closeFuture().sync();

        } finally {
            group.shutdownGracefully();
        }

    }
}

  1. 服務端handler
package netty;

import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

public class NettyServerHandler extends SimpleChannelInboundHandler<String> {
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+" == " +msg);
        channelGroup.forEach(ch->{
            if (channel!=ch) {
                ch.writeAndFlush("[ ke hu duan ]" + channel.remoteAddress() + "傳送了訊息 : " + msg + "\n");
            }else{
                ch.writeAndFlush("[ self ] 傳送了訊息: " + msg + "\n");
            }
        });

    }

    public static void sendAll(String msg){  // 自己琢磨新增的 用於服務端發信息給所有客戶端 目前不知是否有問題
        channelGroup.forEach(channel -> {
            channel.writeAndFlush("服務的公告: "+msg+"\n");
        });
    }

    public void channelActive(ChannelHandlerContext ctx){
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客戶端]"+channel.remoteAddress()+" 上線了 "+sf.format(new Date())+"\n");
        channelGroup.add(channel);
        System.out.println(ctx.channel().remoteAddress()+" 上線了" + "\n");
    }

    public void channelInactive(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[ 客戶端 ] " +channel.remoteAddress()+ " 下線了"+"\n");
        System.out.println(channel.remoteAddress()+" 下線了.\n");
        System.out.println("channelGroup size = "+ channelGroup.size());
    }
}

  1. 客戶端handler
package netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyClientHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        System.out.println(msg.trim());
    }
}

執行結果:
在這裡插入圖片描述
客戶端發訊息:
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述