之前搭建了一个Springboot+Netty服务端的应用,现在搭建一个Springboot+Netty客户端的应用程序
新建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.0.0.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.0自动导入版本-->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Springboot启动类,启动一个Netty的客户端
package com.bootnetty.client;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
*
* Springboot启动类
*
*/
@SpringBootApplication
public class App {
public static void main(String[] args) throws Exception {
/**
* 启动springboot
*/
SpringApplication.run(App.class, args);
/**
* 启动netty客户端服务
*/
int port = 6668;
new BootNettyClient().connect(port, "127.0.0.1");
System.out.println("Hello World!");
}
}
Netty的client类
package com.bootnetty.client;
import com.bootnetty.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>());
/**
* 连接服务端
*/
ChannelFuture f = bootstrap.connect(host, port).sync();
/**
* 等待连接端口关闭
*/
f.channel().closeFuture().sync();
} finally {
/**
* 退出,释放资源
*/
group.shutdownGracefully();
}
}
}
通道初始化
package com.bootnetty.client.channel;
import com.bootnetty.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());
}
}
客户端I/O数据读写处理类
package com.bootnetty.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 < 2; i++) {
message = Unpooled.buffer(req.length);
message.writeBytes(req);
Thread.sleep(10);
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);
}
}
仅仅几个类就将Springboot和Netty结合,启动Springboot应用的同时也启动了Netty的客户端,连接服务端的端口:6668
测试的时候还是使用TCP工具,是服务端的工具:
启动界面如下:
然后启动Springboot+Netty客户端,启动成功后,我们再来看TCP工具上
可以看到客户端已经成功连接上服务端,我们也可以通过这个工具向我们启动的客户端发送数据
至此,Springboot整合Netty的客户端demo开发测试完成!
在实际开发中,我们不可能处处使用TCP工具,服务端和客户端都是使用程序建立连接。