netty学习之路一

迷南。 2022-03-10 12:48 333阅读 0赞

netty学习之路一

  • server端
  • ServerHandler
  • 客户端
  • 客户端handler

客户端给服务端发送数据,服务端再将该数据返回给客户端

server端

  1. public class Server {
  2. public static void main(String[] args) throws Exception{
  3. EventLoopGroup bossGroup = new NioEventLoopGroup(); // 负责处理来自客户端的链接
  4. EventLoopGroup workerGroup = new NioEventLoopGroup();//负责处理任务
  5. ServerBootstrap bootstrap = new ServerBootstrap();//配置类
  6. bootstrap.group(bossGroup,workerGroup)
  7. .channel(NioServerSocketChannel.class)
  8. .childHandler(new ChannelInitializer<SocketChannel>() {
  9. @Override
  10. protected void initChannel(SocketChannel socketChannel) throws Exception {
  11. socketChannel.pipeline().addLast(new ServerHandler());//添加处理器
  12. }
  13. })
  14. .option(ChannelOption.SO_BACKLOG, 128)
  15. .childOption(ChannelOption.SO_KEEPALIVE, true);
  16. ChannelFuture future = bootstrap.bind(8888).sync();
  17. future.channel().closeFuture().sync();//阻塞线程
  18. workerGroup.shutdownGracefully();
  19. bossGroup.shutdownGracefully();
  20. }
  21. }

ServerHandler

  1. /**
  2. * 收到数据时调用
  3. * @param ctx
  4. * @param msg
  5. * @throws Exception
  6. */
  7. @Override
  8. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  9. try{
  10. InetSocketAddress address = (InetSocketAddress)ctx.channel().remoteAddress();
  11. System.out.println(address.getPort());
  12. System.out.println(address.getAddress());
  13. //doing else something
  14. ByteBuf buf = (ByteBuf) msg;
  15. String result = convertByteBufToString(buf);
  16. System.out.println("收到客户端的信息:"+result);
  17. System.out.println("开始响应");
  18. //给客户端响应完成之后,关闭该客户端连接
  19. ctx.writeAndFlush(Unpooled.copiedBuffer(result.getBytes())).addListener(ChannelFutureListener.CLOSE);
  20. System.out.println("响应结束");
  21. }finally {
  22. ReferenceCountUtil.release(msg);
  23. }
  24. }
  25. /**
  26. * 抛出异常时调用
  27. * @param ctx
  28. * @param cause
  29. * @throws Exception
  30. */
  31. @Override
  32. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  33. cause.printStackTrace();
  34. ctx.close();
  35. }
  36. /**
  37. * 将buf转为string
  38. * @param buf
  39. * @return
  40. */
  41. public String convertByteBufToString(ByteBuf buf) {
  42. String str;
  43. if (buf.hasArray()) { // 处理堆缓冲区
  44. str = new String(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes());
  45. } else { // 处理直接缓冲区以及复合缓冲区
  46. byte[] bytes = new byte[buf.readableBytes()];
  47. buf.getBytes(buf.readerIndex(), bytes);
  48. str = new String(bytes, 0, buf.readableBytes());
  49. }
  50. return str;
  51. }

客户端

  1. public class Client {
  2. public static void main(String[] args) throws Exception{
  3. EventLoopGroup workerGroup = new NioEventLoopGroup();//负责处理任务
  4. Bootstrap bootstrap = new Bootstrap();
  5. bootstrap.group(workerGroup)
  6. .channel(NioSocketChannel.class)
  7. .handler(new ChannelInitializer<SocketChannel>() {
  8. @Override
  9. protected void initChannel(SocketChannel socketChannel) throws Exception {
  10. socketChannel.pipeline().addLast(new ClientHandler());
  11. }
  12. })
  13. .option(ChannelOption.SO_BACKLOG, 128)
  14. .option(ChannelOption.SO_KEEPALIVE, true);
  15. ChannelFuture f = bootstrap.connect("127.0.0.1",8888);
  16. f.channel().writeAndFlush(Unpooled.copiedBuffer("中国".getBytes()));
  17. f.channel().closeFuture().sync();
  18. workerGroup.shutdownGracefully();
  19. }
  20. }

客户端handler

  1. public class ClientHandler extends ChannelInboundHandlerAdapter {
  2. @Override
  3. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  4. try {
  5. ByteBuf buf = (ByteBuf)msg;
  6. String response = convertByteBufToString(buf);
  7. System.out.println("收到的响应为:"+response);
  8. }finally {
  9. ReferenceCountUtil.release(msg);
  10. }
  11. }
  12. @Override
  13. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  14. cause.printStackTrace();
  15. ctx.close();
  16. }
  17. public String convertByteBufToString(ByteBuf buf) {
  18. String str;
  19. if (buf.hasArray()) { // 处理堆缓冲区
  20. str = new String(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes());
  21. } else { // 处理直接缓冲区以及复合缓冲区
  22. byte[] bytes = new byte[buf.readableBytes()];
  23. buf.getBytes(buf.readerIndex(), bytes);
  24. str = new String(bytes, 0, buf.readableBytes());
  25. }
  26. return str;
  27. }
  28. }

发表评论

表情:
评论列表 (有 0 条评论,333人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Netty自学-Netty学习()

    什么Netty? Netty是由JBOSS提供的一个java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客