1. 程式人生 > 其它 >netty入門程式碼

netty入門程式碼

伺服器端程式碼

//建立伺服器 
new ServerBootstrap()
//指定eventLoop分組
.group(new NioEventLoopGroup()) //指定channel實現 伺服器選擇NioServerSocketChannel
.channel(NioServerSocketChannel.class)
//新增處理器 當有客戶端來連線時會呼叫 intiChannel方法
.childHandler(new ChannelInitializer<NioSocketChannel>() {
    protected void initChannel(NioSocketChannel nsc) throws Exception {
// 新增netty提供的StringDecode處理器 將ByteBuf物件轉為String nsc.pipeline().addLast(new StringDecoder());
// 新增自己的入站處理器 拿到訊息簡單在控制檯輸出 nsc.pipeline().addLast(new ChannelInboundHandlerAdapter(){ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println(msg); } ); }
//繫結 8080埠 }).bind(8080);

 客戶端程式碼

//啟動客戶端  指定eventLoop
new Bootstrap().group(new NioEventLoopGroup())
//指定channel實現客戶端選擇NioSocketChannel
.channel(NioSocketChannel.class)
//新增處理器
.handler(new ChannelInitializer<NioSocketChannel>() {
      @Override
      protected void initChannel(NioSocketChannel ch) throws Exception {
           //netty提供的StringEncoder
           ch.pipeline().addLast(new StringEncoder());
      }
}).connect(new InetSocketAddress("localhost", 8080))
//同步等待nio執行緒建立連線 同步方法
.sync()
//建立連線成功後獲取channel向伺服器發出資料
.channel().writeAndFlush("傳送的資料");

  先啟動伺服器在啟動客戶端,伺服器就會收到客戶端傳送的資料,netty的入門程式碼