package com.msb.socket;/** * @Author bingor * @Date 2022/11/16 13:39 * @Description: com.msb.socket * @Version: 1.0 */ import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; /** *@ClassName Client *@Description TODO *@Author bingor *@Date 2022/11/16 13:39 *@Version 3.0 */ public class Client { public void connect() { //线程池 EventLoopGroup group = new NioEventLoopGroup(1); Bootstrap bootstrap = new Bootstrap(); try { ChannelFuture future = bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ClientChannelInitializer()) .connect("localhost", 8888); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if(channelFuture.isSuccess()) { System.out.println("connected!"); } else { System.out.println("not connect!"); } } }); future.sync(); future.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } } public static void main(String[] args) { Client client = new Client(); client.connect(); } } class ClientChannelInitializer extends ChannelInitializer { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new ClientHandler()); } } class ClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // super.channelRead(ctx, msg); ByteBuf buf = (ByteBuf) msg; byte[] bytes = new byte[buf.readableBytes()]; buf.getBytes(buf.readerIndex(), bytes); System.out.println(new String(bytes)); } }