
网络编程复习(六):Netty入门Demo
serverHandler处理类:
发布日期:2021-11-13 10:21:51
浏览次数:3
分类:技术文章
本文共 4495 字,大约阅读时间需要 14 分钟。
关于Netty,可以看做是对JDK的nio API的封装,提供了更简单的实现,同时性能,功能更加丰富以及相对应的安全机制,对于Netty的学习,大家可以访问如下网址,里面讲解的很详细,这里仅写一个小demo作为入门。
学习网址:http://ifeve.com/netty5-user-guide/
server:
package 网络编程_Netty;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;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.NioServerSocketChannel;public class Server {
private int port;
public Server(int port){
this.port = port;
}
public void run() throws Exception{
/*定义两个处理IO操作的多线程时间循环器,boss一般用来接受客户端连接,workers用来处理已经被接
收的连接,这里使用NIOEvent处理tcp协议,还有很多种实现类用于处理不同的传输协议。
*/
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup workers = new NioEventLoopGroup();
try {
//ServerBootstrap是服务端的启动NIO服务的辅助类,用于设置一些服务的参数
ServerBootstrap bootstrap = new ServerBootstrap();
//将两个事件循环器加入到辅助类中
bootstrap.group(boss, workers)
//指定具体的通道连接方式
.channel(NioServerSocketChannel.class)
//使用childHandler指定具体的事件处理类
.childHandler(new ChannelInitializer() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ServerHandler());
}
})
//关闭BACKLOG参数作用需要了解TCP底层三次握手机制,底部维持了2个队列,当两个队列和大于BACKLOG时,服务端会拒绝客户端连接
.option(ChannelOption.SO_BACKLOG, 128)
//保持存活状态
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = bootstrap.bind(port).sync();//绑定端口
f.channel().closeFuture().sync();//相当于阻塞
} finally {
workers.shutdownGracefully();//关闭操作
boss.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception{
new Server(8888).run();
}}
serverHandler处理类:
package 网络编程_Netty;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelFutureListener;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;/** * 处理器类,处理器是由netty生成用来处理IO事件的 * @author lihao * */public class ServerHandler extends ChannelHandlerAdapter{client:
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf)msg;
byte[] bys = new byte[buf.readableBytes()];
buf.readBytes(bys);
String accept = new String(bys,"utf-8");
System.out.println(accept);
String response = new String("你好,服务器已经接受到你的请求");
ChannelFuture writeAndFlush = ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));//wirte的时候会手动的释放msg
writeAndFlush.addListener(ChannelFutureListener.CLOSE);//监听写数据进程,当数据写出完毕关闭连接
}
}
package 网络编程_Netty;import io.netty.bootstrap.Bootstrap;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;public class Client {clientHandler事件处理类
public static void main(String[] args) throws Exception {
EventLoopGroup workers = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workers)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ClientHandler());
}
});
ChannelFuture f = bootstrap.connect("127.0.0.1",8888).sync();
f.channel().writeAndFlush(Unpooled.copiedBuffer("hello netty".getBytes()));
f.channel().closeFuture().sync();
workers.shutdownGracefully();
}}
package 网络编程_Netty;import io.netty.buffer.ByteBuf;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;import io.netty.util.ReferenceCountUtil;public class ClientHandler extends ChannelHandlerAdapter{
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
ByteBuf buf = (ByteBuf)msg;
byte[] bys = new byte[buf.readableBytes()];
buf.readBytes(bys);
String accept = new String(bys,"utf-8");
System.out.println(accept);
} finally {
ReferenceCountUtil.release(msg);
}
}
}
转载地址:https://blog.csdn.net/Lee_Ho_/article/details/78128340 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
网站不错 人气很旺了 加油
[***.200.74.241]2022年05月27日 17时43分20秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
最新文章
check style
2019-12-07 20:38:45
ksh set env
2019-12-07 20:38:45
shell cmd
2019-12-07 20:38:45
hutool-poi
2019-12-07 20:38:46
使用spring加载properties文件
2019-12-07 20:38:44
httpclient4.5调用接口
2019-12-07 20:38:44
DB Connection
2019-12-07 20:38:44
DataConstant
2019-12-07 20:38:45
ExcelReader
2019-12-07 20:38:45
引用jar版本错误
2019-12-07 20:38:43
手工初始化spring beans
2019-12-07 20:38:43
CAS-3.2.1自定义客户端登录界面----完整篇
2019-12-07 20:38:43
SVN环境搭建
2019-12-07 20:38:43
大数据的批量更新方法
2019-12-07 20:38:43
递归去除集合中的空格(集合中可能包括集合,Map、List)
2019-12-07 20:38:43
Spring+CXF+IBatis详细介绍及下载
2019-12-07 20:38:41
tomcat下摘要认证(数据库配置用户角色)+java代码模拟请求
2019-12-07 20:38:41
后台JS校验框架
2019-12-07 20:38:41
获得某年某月的第N周的日期
2019-12-07 20:38:42
linux下:apache2.2.27 + tomcat7.0 + openssl-1.0.1g(集群+session共享|摘要认证|HTTPS)
2019-12-07 20:38:42