之前搭建了一个Springboot+Netty服务端的应用,既然有服务端,自然也有客户端的应用,现在搭建一个Springboot+Netty客户端的应用Demo程序,也是使用TCP工具来进行测试,最终将客户端和服务端作为一个具体的应用来测试。
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-parent
2.1.6.RELEASE
org.springframework.boot
spring-boot-starter-web
io.netty
netty-all
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");
}
}
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());
System.out.println("netty client start success!");
/**
* 连接服务端
*/
ChannelFuture f = bootstrap.connect(host, port).sync();
/**
* 等待连接端口关闭
*/
f.channel().closeFuture().sync();
} finally {
/**
* 退出,释放资源
*/
group.shutdownGracefully();
}
}
}
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 extends ChannelInitializer {
@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());
}
}
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);
}
}