一 整合
由于本人的学过的技术太多太乱了,于是决定一个一个的整合到一个springboot项目里面。
以整合功能
spring-boot,FusionChart,thymeleaf,vue,ShardingJdbc,mybatis-generator,微信分享授权,drools,spring-security,spring-jpa,webjars,Aspect,drools-drt,rabbitmq,zookeeper,mongodb,mysql存储过程,前端的延迟加载
这次就来整合下netty
二
之前都是用java源码来做socket连接,现在试一下netty。
三 代码
客户端
public classNettyClientDemo {public static String host = "127.0.0.1";public static int port = 1234;public static voidmain(String[] args) throws Exception {
EventLoopGroup group= newNioEventLoopGroup();try{//创建 Bootstrap
Bootstrap b = newBootstrap();//指定 EventLoopGroup 以处理客户端事件;需要适用于 NIO 的实现
b.group(group)//适用于 NIO 传输的Channel 类型
.channel(NioSocketChannel.class)//设置服务器的InetSocketAddress
.remoteAddress(newInetSocketAddress(host, port))//在创建Channel时,向 ChannelPipeline中添加一个 EchoClientHandler实例
.handler(new ChannelInitializer() {
@Overridepublic voidinitChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(newEchoClientHandler());
}
});//连接到远程节点,阻塞等待直到连接完成
ChannelFuture f =b.connect().sync();//阻塞,直到Channel 关闭
f.channel().closeFuture().sync();
}finally{//关闭线程池并且释放所有的资源
group.shutdownGracefully().sync();
}
}
}
服务器
public classNettyServerDemo {public static final int port = 1234;public static voidmain(String[] args) throws Exception {
final EchoServerHandler serverHandler= newEchoServerHandler();//(1) 创建EventLoopGroup
EventLoopGroup group = newNioEventLoopGroup();try{//(2) 创建ServerBootstrap
ServerBootstrap b = newServerBootstrap();
b.group(group)//(3) 指定所使用的 NIO 传输 Channel
.channel(NioServerSocketChannel.class)//(4) 使用指定的端口设置套接字地址
.localAddress(newInetSocketAddress(port))//(5) 添加一个EchoServerHandler到于Channel的 ChannelPipeline
.childHandler(new ChannelInitializer() {
@Overridepublic voidinitChannel(SocketChannel ch) throws Exception {//EchoServerHandler 被标注为@Shareable,所以我们可以总是使用同样的实例//这里对于所有的客户端连接来说,都会使用同一个 EchoServerHandler,因为其被标注为@Sharable,//这将在后面的章节中讲到。
ch.pipeline().addLast(serverHandler);
}
});//(6) 异步地绑定服务器;调用 sync()方法阻塞等待直到绑定完成
ChannelFuture f =b.bind().sync();
System.out.println(NettyServerDemo.class.getName() +
"started and listening for connections on" +f.channel().localAddress());//(7) 获取 Channel 的CloseFuture,并且阻塞当前线程直到它完成
f.channel().closeFuture().sync();
}finally{//(8) 关闭 EventLoopGroup,释放所有的资源
group.shutdownGracefully().sync();
}
}
}
pom.xml
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
junit
junit
4.2
test
io.netty
netty-all
5.0.0.Alpha1
四 总结
pom.xml拉上来是因为百度的教程大多没有,而netty似乎向下兼容没有做的很好。
代码理解有点网络编程基础的基本都知道是什么意思。
EchoServerHandler 和 EchoClientHandler为了更加明确的看出连接的效果,并没有用默认的而是自己新建了一个,修改了一下打印信息。