重写我们需要的方法,channelActive(新的连接被建立时调用),channelRead(读取数据),channelReadComplete(读取最后的一条信息),exceptionCaught(发生异常时调用)
Netty实现一个客户端 客户端 /** * @author monkjavaer * @date 2019/7/18 17:17 */ public class NettyClient { private static Logger LOGGER = LoggerFactory.getLogger(NettyClient.class); public static String IP = "127.0.0.1"; public static int PORT = 8080; public static void main(String[] args) { EventLoopGroup client = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(client) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY,true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new NettyClientHandler()); } }); ChannelFuture f = bootstrap.connect(IP,PORT).sync(); f.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); }finally { client.shutdownGracefully(); } } }客户端这里只创建一个线程组即可
帮助类这里使用Bootstrap
设置通道为NioSocketChannel
其他类容和服务器雷士
和服务器建立连接
客户端处理类 /** * @author monkjavaer * @date 2019/7/18 17:26 */ public class NettyClientHandler extends ChannelInboundHandlerAdapter { private static Logger LOGGER = LoggerFactory.getLogger(NettyServerHandler.class); /** * 新的连接被建立时调用 * * @param ctx * @throws Exception */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { LOGGER.info("server {} connected.", ctx.channel().remoteAddress()); ctx.writeAndFlush(Unpooled.copiedBuffer("hello server!", CharsetUtil.UTF_8)); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf byteBuf = (ByteBuf) msg; //获取缓冲区可读字节数 int readableBytes = byteBuf.readableBytes(); byte[] bytes = new byte[readableBytes]; byteBuf.readBytes(bytes); LOGGER.info("readableBytes is{},client received message:{}", readableBytes, new String(bytes, StandardCharsets.UTF_8)); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOGGER.error("server exceptionCaught,{}",cause.getMessage()); ctx.close(); } }