Springboot+Netty搭建基于TCP协议的客户端(二)

之前搭建了一个Springboot+Netty服务端的应用,既然有服务端,自然也有客户端的应用,现在搭建一个Springboot+Netty客户端的应用Demo程序,也是使用TCP工具来进行测试,最终将客户端和服务端作为一个具体的应用来测试。

1、新建Springboot的maven项目,pom.xml文件导入依赖包

<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.6.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<dependencies>

		<!--web模块的启动器-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!--  netty依赖 springboot2.x自动导入版本-->
		<dependency>
			<groupId>io.netty</groupId>
			<artifactId>netty-all</artifactId>
		</dependency>


	</dependencies>

2、Springboot启动类,启动一个Netty的客户端

package boot.netty.base.client;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;

/**
 * Hello world!
 *
 */
@SpringBootApplication
@EnableAsync
public class BootNettyApplication implements CommandLineRunner{
    public static void main( String[] args )
    {
    	/**
    	 * 启动springboot
    	 */
		SpringApplication app = new SpringApplication(BootNettyApplication.class);
		//app.setWebApplicationType(WebApplicationType.NONE);//不启动web服务
		app.run(args);

        System.out.println( "Hello World!" );
    }

    @Async
	@Override
	public void run(String... args) throws Exception {
		/**
		 * 使用异步注解方式启动netty客户端服务
		 */
		int port = 8888;
		new BootNettyClient().connect(port, "127.0.0.1");

	}
}

3、Netty的client类

package boot.netty.base.client;


import boot.netty.base.client.channel.BootNettyChannelInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 *
 * netty 客户端
 *
 */
public class BootNettyClient {

	public void connect(int port, String host) throws Exception{

		/**
		 * 客户端的NIO线程组
		 *
		 */
        EventLoopGroup group = new NioEventLoopGroup();

        try {
        	/**
        	 * Bootstrap 是一个启动NIO服务的辅助启动类 客户端的
        	 */
        	Bootstrap bootstrap = new Bootstrap();
        	/**
        	 * 设置group
        	 */
        	bootstrap = bootstrap.group(group);
        	/**
        	 * 关联客户端通道
        	 */
        	bootstrap = bootstrap.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
        	/**
        	 * 设置 I/O处理类,主要用于网络I/O事件,记录日志,编码、解码消息
        	 */
        	bootstrap = bootstrap.handler(new BootNettyChannelInitializer<SocketChannel>());

        	System.out.println("netty client start success!");

        	/**
        	 * 连接服务端
        	 */
        	ChannelFuture f = bootstrap.connect(host, port).sync();
        	/**
        	 * 等待连接端口关闭
        	 */
        	f.channel().closeFuture().sync();

		} finally {
			/**
			 * 退出,释放资源
			 */
			group.shutdownGracefully();
		}

	}


}

4、通道初始化

package boot.netty.base.client.channel;

import boot.netty.base.client.adapter.BootNettyChannelInboundHandlerAdapter;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * 通道初始化
 *
 */
public class BootNettyChannelInitializer<SocketChannel> extends ChannelInitializer<Channel> {

	@Override
	protected void initChannel(Channel ch) throws Exception {
		// ChannelOutboundHandler,依照逆序执行(从下往上)
        ch.pipeline().addLast("encoder", new StringEncoder());
        // 属于ChannelInboundHandler,依照顺序执行(从上往下)
        ch.pipeline().addLast("decoder", new StringDecoder());
        /**
         * 自定义ChannelInboundHandlerAdapter
         */
        ch.pipeline().addLast(new BootNettyChannelInboundHandlerAdapter());

	}

}

5、客户端I/O数据读写处理类

package boot.netty.base.client.adapter;

import java.io.IOException;
import java.net.InetSocketAddress;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 *
 * I/O数据读写处理类
 *
 */
public class BootNettyChannelInboundHandlerAdapter extends ChannelInboundHandlerAdapter{

    /**
     * 从服务端收到新的数据时,这个方法会在收到消息时被调用
     *
     * @param ctx
     * @param msg
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception, IOException
    {
    	System.out.println("channelRead:read msg:"+msg.toString());
        //回应服务端
        ctx.write("I got server message thanks server!");
    }

    /**
     * 从服务端收到新的数据、读取完成时调用
     *
     * @param ctx
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws IOException
    {
    	System.out.println("channelReadComplete");
    	ctx.flush();
    }

    /**
     * 当出现 Throwable 对象才会被调用,即当 Netty 由于 IO 错误或者处理器在处理事件时抛出的异常时
     *
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws IOException
    {
    	System.out.println("exceptionCaught");
        cause.printStackTrace();
        ctx.close();//抛出异常,断开与客户端的连接
    }

    /**
     * 客户端与服务端第一次建立连接时 执行
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception, IOException
    {
        super.channelActive(ctx);
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = insocket.getAddress().getHostAddress();
        System.out.println("channelActive:"+clientIp+ctx.name());
    	ByteBuf message = null;
    	byte[] req = ("I am client once").getBytes();
    	for(int i = 0; i < 5; i++) {
    		message = Unpooled.buffer(req.length);
    		message.writeBytes(req);
    		Thread.sleep(5000);
    		ctx.writeAndFlush(message);
    	}

    }

    /**
     * 客户端与服务端 断连时 执行
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception, IOException
    {
        super.channelInactive(ctx);
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = insocket.getAddress().getHostAddress();
        ctx.close(); //断开连接时,必须关闭,否则造成资源浪费
        System.out.println("channelInactive:"+clientIp);
    }



}

6、测试的时候还是使用TCP工具,是服务端的工具,工具配合程序一次测试。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个开源的Java开发框架,用于开发微服务和基于RESTful架构的应用。Netty 是一个用于构建高性能、事件驱动的网络应用程序的Java框架。Netty 提供了TCP 和 UDP 传输协议的支持,因此可以方便地使用Netty构建TCP客户端。 在Spring Boot中使用Netty构建TCP客户端的步骤如下: 1. 在pom.xml文件中添加Netty的依赖项: ``` <dependencies> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>x.x.x</version> </dependency> </dependencies> ``` 2. 创建一个TCP客户端的处理器类,继承Netty的SimpleChannelInboundHandler抽象类,重写相应的方法来处理数据。 ``` public class TcpClientHandler extends SimpleChannelInboundHandler<String> { @Override public void channelActive(ChannelHandlerContext ctx) { // 在连接建立时发送数据 ctx.writeAndFlush("Hello Server!"); } @Override public void channelRead0(ChannelHandlerContext ctx, String message) { // 处理接收到的数据 System.out.println("Received from server: " + message); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 处理异常情况 cause.printStackTrace(); ctx.close(); } } ``` 3. 创建一个Spring Boot的启动类,并在其中配置Netty的相关参数和创建TCP客户端Bootstrap实例。 ``` @SpringBootApplication public class TcpClientApplication { public static void main(String[] args) { SpringApplication.run(TcpClientApplication.class, args); } @Bean public CommandLineRunner tcpClientRunner() { return args -> { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new TcpClientHandler()); } }); ChannelFuture future = bootstrap.connect("localhost", 8888).sync(); future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } }; } } ``` 以上就是使用Spring BootNetty构建TCP客户端的基本步骤。通过以上配置,可以编写相应的业务逻辑来与服务器进行通信,实现相关功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值