上代码
-
建一个EchoClient类
public class EchoClient { @Value("${netty.host}") private String host; @Value("${netty.port}") private int port; //@PostConstruct //用tomcat容器要加上这个,这里没有用tomcat跑 public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host, port)) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoClientHandler()); } }); ChannelFuture f = b.connect().sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } } }
-
建EchoClientHandler类
@ChannelHandler.Sharable public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> { @Override public void channelActive(ChannelHandlerContext ctx) { ctx.writeAndFlush(Unpooled.copiedBuffer("Hello Netty", CharsetUtil.UTF_8)); } //消息读取有两个方法,channelRead和channelRead0,其中channelRead0可以读取泛型 @Override public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) { System.out.println("客户端接收到数据:" + in.toString(CharsetUtil.UTF_8)); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
-
启动类:
@SpringBootApplication public class ClientApplication implements CommandLineRunner { @Autowired private EchoClient echoclient; public static void main(String[] args) { SpringApplication.run(ClientApplication.class, args); } @Bean //凡是子类及带属性、方法的类都注册Bean到Spring中,交给它管理,之前没有这个报错了; public EchoClient echoClient(){ return new EchoClient(); } @Override public void run(String... strings) throws Exception { //EchoClient echoclient = new EchoClient(); echoclient.start(); } }
-
application.proporty:
netty.port=7000 netty.host=127.0.0.1
测试结果
用上一章节的服务器测试
说明成功了。
回顾
- 照例new个NioEventLoopGroup,Bootstrap,配参数,加channel,connect().sync()。
- EchoClientHandler接收数据,处理事务。
channelActive——在到服务器的连接建立之后将被调用
channelRead0——从服务器收到一条消息时被调用
exceptionCaught——异常被调用