首页 > 其他分享 >Netty的第一个例子

Netty的第一个例子

时间:2022-10-19 16:04:25浏览次数:46  
标签:Netty 第一个 netty 例子 io new import public channel

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 TimeServer {

public void bind(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();

try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChildChannelHandler());
//绑定端口,同步等待成功
ChannelFuture future = serverBootstrap.bind(port).sync();
//等待服务端监听端口关闭
future.channel().closeFuture().sync();

} catch (Exception e) {
e.printStackTrace();
} finally {
//优雅退出
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}

private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new TimeServerHandler());
}
}

public static void main(String[] args) throws Exception {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
new TimeServer().bind(port);
}

}

 

TimeServerHandler

 

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeServerHandler extends ChannelInboundHandlerAdapter {

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "UTF-8");
System.out.println("The time server receive order:" + body);

String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";

ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp);
ctx.flush();
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
}

TimeClient

import io.netty.bootstrap.Bootstrap; 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.NioSocketChannel; public class TimeClient { public void connect(int port, String host) throws Exception { //配置客户端NIO线程组 EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup) .channel(NioSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new TimeClientHandler()); } }); //发起异步链接操作 ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); //等待客户端链路关闭 channelFuture.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { //优雅退出,释放NIO线程组 eventLoopGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port = 8080; if (args != null && args.length > 0) { try { port = Integer.parseInt(args[0]); } catch (Exception e) { //采用默认值 e.printStackTrace(); } } new TimeClient().connect(port, "127.0.0.1"); }

TimeClientHandler
Time
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class TimeClientHandler extends ChannelInboundHandlerAdapter {

private ByteBuf firstMessage;

public TimeClientHandler() {
byte[] req = "QUERY TIME ORDER".getBytes();
this.firstMessage = Unpooled.buffer(req.length);
this.firstMessage.writeBytes(req);
}

public void channelActive(ChannelHandlerContext ctx) {
ctx.writeAndFlush(this.firstMessage);
}

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf)msg;
byte[] req = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(req);
String body = new String(req, "UTF-8");
System.out.println("Now is " + body);
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
}


 


Netty的第一个例子_.net

越努力,越幸运,欢迎关注我的个人技术公众号


标签:Netty,第一个,netty,例子,io,new,import,public,channel
From: https://blog.51cto.com/woshisap/5775590

相关文章

  • 拿到40k的offer入职,第一个任务就是搭建一套最牛监控平台!
    转载:以下文章来源于架构悟道 ,作者veezeanhttps://mp.weixin.qq.com/s?__biz=MzU0OTk3ODQ3Ng==&mid=2247565686&idx=1&sn=f7887ff74a54ca4c80859763cca712cc&chksm=fba429......
  • 通过netty把百度地图API获取的地理位置从Android端发送到Java服务器端
    本篇记录我在实现时的思考过程,写给之后可能遇到困难的我自己也给到需要帮助的人。写的比较浅显,见谅。在写项目代码的时候,需要把Android端的位置信息传输到服务器端,通过Ne......
  • 我的第一个项目
    网易云项目马上快毕业了,都要面临找工作的难题,这个无法避免,其实还是挺想找一行前端开发的工作,我对这个行业的兴趣也比较浓厚。我的前端之路基本都靠自学,我知道找工作肯定......
  • 第一个自动化测试程序
    importtimefromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfromselenium.webdriver.edge.serviceimportServicedefloginAndCheck......
  • [答题赛(第11轮)]第一个全对者发红包
    单选题。在公众号留言回答。第一个全答对着获得奖金红包。本消息发布24小时后公布答案和得奖者。1、某研发团队的任务是开发公司现有产品的“可穿戴设备版本”。公司现有产......
  • [答题赛(第9轮)]第一个全对者发红包
    单选题。在公众号留言回答。第一个全答对着获得奖金红包。本消息发布24小时后公布答案和得奖者。1、以下是最近一段时间发生的著名事件,哪一个和阿布思考法相关度最大?A)李......
  • Netty源码分析——客户端接入accept过程
    基于Netty源代码版本:netty-all-4.1.33.Finalnetty中的reactor线程netty中最核心的东西莫过于两种类型的reactor线程,可以看作netty中两种类型的发动机,驱动着netty整个框架......
  • iCells(Excel插件)第一个版本正式发布
    一、界面二、功能(一)支持连续撤销,由于时间有限,未能开发全部的撤销功能,后期将逐步加入。(二)多种号码校验,特别是身份证校验,对于身份证录入后的校验简直是神器。(三)随机功能......
  • Netty概述
    Netty概述1.*原生NIO存在的问题NIO的类库和API繁杂,使用麻烦:需要熟练掌握Selector、ServerSocketChannel、SocketChannel、ByteBuffer等。需要具备其他的额外技能:要熟......
  • 软光栅渲染器开发01-背景介绍以及第一个三角形
    1.为什么是软光栅渲染器正常来讲,一个有志于进行游戏或者图形开发的人,在实际的生产环境中,大多是依赖于游戏引擎或者常见图形API(OpenGL,DirectX,Vulkan)的封装来进行工作......