netty socket 客服端編程

來源:互聯網
上載者:User

標籤:bar   nio   複製   gif   rri   main   shutdown   cli   line   

package com.ming.netty.nio; 2  3 import io.netty.bootstrap.Bootstrap; 4 import io.netty.channel.ChannelFuture; 5 import io.netty.channel.ChannelInitializer; 6 import io.netty.channel.ChannelOption; 7 import io.netty.channel.EventLoopGroup; 8 import io.netty.channel.nio.NioEventLoopGroup; 9 import io.netty.channel.socket.SocketChannel;10 import io.netty.channel.socket.nio.NioSocketChannel;11 12 /**13  * netty 用戶端類比14  * @author mingge15  *16 */17 public class TimeClient {18 19 20 public static void main(String[] args) throws Exception{21 new TimeClient().connect("127.0.0.1", 8400);22  }23 24 public void connect(String addr,int port) throws Exception{25 EventLoopGroup group=new NioEventLoopGroup();26 try {27 Bootstrap b=new Bootstrap();28 b.group(group).channel(NioSocketChannel.class)29 .option(ChannelOption.TCP_NODELAY, true)30 .handler(new ChannelInitializer<SocketChannel>() {31 public void initChannel(SocketChannel ch) throws Exception{32 ch.pipeline().addLast(new TimeClientHandler());33  }34  });35 ChannelFuture f=b.connect(addr,port);36 f.channel().closeFuture().sync();//等待用戶端關閉串連37 } catch (Exception e) {38 // TODO: handle exception39 }finally{40  group.shutdownGracefully();41  }42  }43 }
 1 package com.ming.netty.nio; 2  3 import io.netty.buffer.ByteBuf; 4 import io.netty.buffer.Unpooled; 5 import io.netty.channel.ChannelHandlerAdapter; 6 import io.netty.channel.ChannelHandlerContext; 7  8 public class TimeClientHandler extends ChannelHandlerAdapter { 9 10 private final ByteBuf byteMsg;11 12 public TimeClientHandler() {13 byte[] req="我是請求資料哦".getBytes();14 byteMsg=Unpooled.buffer(req.length);15  byteMsg.writeBytes(req);16  }17 18  @Override19 public void channelActive(ChannelHandlerContext ctx) throws Exception {20  ctx.writeAndFlush(byteMsg);21  }22 23  @Override24 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {25 ByteBuf buf=(ByteBuf)msg;26 byte[] req=new byte[buf.readableBytes()];27  buf.readBytes(req);28 String body=new String(req,"GBK");29 System.out.println("body:"+body);30  }31 32  @Override33 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {34 //釋放資源35  ctx.close();36  }37 38 39 }

netty socket 客服端編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.