之前搭建了一个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工具,是服务端的工具:
仅仅几个类就将Springboot和Netty结合,启动Springboot应用的同时也启动了Netty的客户端,连接服务端的端口:6668
启动界面如下:(图片上的端口是6668实际端口是8888,看具体需要更改)
7、然后启动Springboot+Netty客户端,启动成功后,我们再来看TCP工具上
可以看到客户端已经成功连接上服务端,我们也可以通过这个工具向我们启动的客户端发送数据
至此,Springboot整合Netty的客户端demo开发测试完成!
在实际开发中,我们不可能处处使用TCP工具,服务端和客户端都是使用程序建立连接。
8、Springboot+Netty的源码案例
注意:在源码案例中,服务端的案例源码有一个地方需要修改顺序
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()); } }