分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

netty基本用法

发布时间:2023-09-06 01:07责任编辑:彭小芳关键词:暂无标签

1.客户端

①HelloClient.java

public class HelloClient {public static String host = "127.0.0.1"; ????public static int port = 7878; ?????/** ?????* @param args ?????* @throws InterruptedException ??????* @throws IOException ??????*/ ????public static void main(String[] args) throws InterruptedException, IOException { ????????EventLoopGroup workGroup = new NioEventLoopGroup(); ????????try { ????????????Bootstrap b = new Bootstrap(); ????????????b.group(workGroup) ????????????.channel(NioSocketChannel.class) ????????????.handler(new HelloClientInitializer()); ?????????????// 连接服务端 ????????????ChannelFuture future = b.connect(host, port).sync(); ?????????????????????????// 控制台输入 ????????????BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); ????????????for (;;) { ????????????????String line = in.readLine(); ????????????????if (line == null) { ????????????????????continue; ????????????????} ????????????????/* ?????????????????* 向服务端发送在控制台输入的文本 并用"\r\n"结尾 ?????????????????* 之所以用\r\n结尾 是因为我们在handler中添加了 DelimiterBasedFrameDecoder 帧解码。 ?????????????????* 这个解码器是一个根据\n符号位分隔符的解码器。所以每条消息的最后必须加上\n否则无法识别和解码 ?????????????????* */ ????????????????future.channel().writeAndFlush(line + "\r\n"); ????????????} ????????} finally { ????????????// The connection is closed automatically on shutdown. ????????workGroup.shutdownGracefully(); ????????} ????}}

②HelloClientInitializer.java

主要功能是完成客户端的编解码工作

public class HelloClientInitializer extends ChannelInitializer<SocketChannel> { ????protected void initChannel(SocketChannel ch) throws Exception { ????????ChannelPipeline pipeline = ch.pipeline(); ?????????/* ?????????* 这个地方的 必须和服务端对应上。否则无法正常解码和编码 ?????????* ??????????* 解码和编码 我将会在下一张为大家详细的讲解。再次暂时不做详细的描述 ?????????* ??????????* */ ????????pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); ????????pipeline.addLast("decoder", new StringDecoder()); ????????pipeline.addLast("encoder", new StringEncoder()); ?????????????????// 客户端的逻辑 ????????pipeline.addLast("handler", new HelloClientHandler()); ???}}

③ HelloClientHandler.java

业务处理类,主要有三个方法

客户端建立连接时调用:channelActive方法

客户端接收服务端消息时调用:channelRead0方法

连接断开时调用:channelInactive方法

public class HelloClientHandler extends SimpleChannelInboundHandler<String> { ????@Override ????protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { ?????????????????System.out.println("Server say : " + msg); ????} ?????????@Override ????public void channelActive(ChannelHandlerContext ctx) throws Exception { ????????System.out.println("Client active "); ????????super.channelActive(ctx); ????} ?????@Override ????public void channelInactive(ChannelHandlerContext ctx) throws Exception { ????????System.out.println("Client close "); ????????super.channelInactive(ctx); ????}}

 2.服务端

①HelloServer.java

public class HelloServer { /** ????* 服务端监听的端口地址 ????*/ ???private static final int portNumber = 7878; ???????public static void main(String[] args) throws InterruptedException { ???//第一个线程组用于接收client连接 ???????EventLoopGroup bossGroup = new NioEventLoopGroup(); ???????//第二个线程组用于具体的业务处理 ???????EventLoopGroup workerGroup = new NioEventLoopGroup(); ???????try { ???????//创建一个辅助类Boosatrap用于对Server进行一系列的配置 ???????????ServerBootstrap b = new ServerBootstrap(); ???????????//将两个线程组加入进来 ???????????b.group(bossGroup, workerGroup); ???????????//指定使用NioServerSocketChannel这种类型的通道 ???????????b.channel(NioServerSocketChannel.class); ???????????//一定要使用childHandler绑定具体的事件处理器 ???????????b.childHandler(new HelloServerInitializer()); ???????????????????????//SocketChannel通道的配置项(保持连接) ???????????b.option(ChannelOption.SO_KEEPALIVE, true); ???????????????????????// 服务器绑定端口监听 ???????????ChannelFuture f = b.bind(portNumber).sync(); ???????????// 监听服务器关闭监听 ???????????f.channel().closeFuture().sync(); ???????????// 可以简写为 ???????????/* b.bind(portNumber).sync().channel().closeFuture().sync(); */ ???????} finally { ???????????bossGroup.shutdownGracefully(); ???????????workerGroup.shutdownGracefully(); ???????} ???}}

 ②HelloServerInitializer.java

主要功能是完成服务端的编解码工作

public class HelloServerInitializer extends ChannelInitializer<SocketChannel> { ????@Override ????protected void initChannel(SocketChannel ch) throws Exception { ????????ChannelPipeline pipeline = ch.pipeline(); ?????????// 以("\n")为结尾分割的 解码器 ????????pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); ?????????// 字符串解码 和 编码 ????????pipeline.addLast("decoder", new StringDecoder()); ????????pipeline.addLast("encoder", new StringEncoder()); ?????????// 自己的逻辑Handler ????????pipeline.addLast("handler", new HelloServerHandler()); ????}}

 ③HelloServerHandler.java

服务端的业务处理类,主要包括channelRead0(),channelActive()方法

channelActive()建立连接时触发

channelRead0()接收客户端消息

public class HelloServerHandler extends SimpleChannelInboundHandler<String> { ????@Override ????protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { ????????// 收到消息直接打印输出 ????????System.out.println(ctx.channel().remoteAddress() + " Say : " + msg); ?????????????????// 返回客户端消息 - 我已经接收到了你的消息 ????????ctx.writeAndFlush("Received your message !\n"); ????} ?????????/* ?????* ??????* 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候) ?????* ??????* channelActive 和 channelInActive 在后面的内容中讲述,这里先不做详细的描述 ?????* */ ????@Override ????public void channelActive(ChannelHandlerContext ctx) throws Exception { ?????????????????System.out.println("RamoteAddress : " + ctx.channel().remoteAddress() + " active !"); ?????????????????ctx.writeAndFlush( "Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n"); ?????????????????super.channelActive(ctx); ????}}

netty基本用法

原文地址:http://www.cnblogs.com/cowboys/p/7605635.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved