Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to get a simple understanding of the use of netty by getting started with demo

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces you how to get started with demo simply to understand the use of netty, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Preface

Recently worked on a project:

Approximate requirements: multiple temperature sensors continue to send temperature data to the java service, which uses socket to send data; the data begins and ends with a $sign, and finally stores the processed data in the database

I think of the processing method: using netty to receive and process the data, and then using mybatis to store the processed data into the database

I have never used netty before, but I have seen a lot of articles about netty on the Internet. Now I will take advantage of this project to write about what I have learned and the problems I have encountered, and how to solve them.

The next few articles are written around this project; this article focuses on the introduction to netty demo

Text

Code part

Create a new maven project

First import in pom.xml:

Io.netty netty-all 5.0.0.Alpha1

Server 1. DiscardServer class, server of netty

Public class DiscardServer {public void run (int port) throws Exception {EventLoopGroup bossGroup = new NioEventLoopGroup (); EventLoopGroup workerGroup = new NioEventLoopGroup (); System.out.println ("ready to run port:" + port); try {ServerBootstrap b = new ServerBootstrap (); b = b.group (bossGroup, workerGroup) .channel (NioServerSocketChannel.class) .option (ChannelOption.SO_BACKLOG, 128) .childHandler (new ChildChannelHandler ()); / / bind port, wait for success ChannelFuture f = b.bind (port). Sync () / wait for the service listening port to close f.channel (). CloseFuture (). Sync ();} finally {/ / exit, release thread resources workerGroup.shutdownGracefully (); bossGroup.shutdownGracefully ();}} public static void main (String [] args) throws Exception {new DiscardServer () .run (8080);}}

2. ChildChannelHandler class:

Public class ChildChannelHandler extends ChannelInitializer {protected void initChannel (SocketChannel socketChannel) throws Exception {socketChannel.pipeline () .addLast (new DiscardServerHandler ();}}

3. DiscardServerHandler class

Here is the inherited ChannelHandlerAdapter class, of course, can also inherit other classes, such as SimpleChannelInboundHandler,ChannelInboundHandlerAdapter can

Public class DiscardServerHandler extends ChannelHandlerAdapter {@ Override public void channelRead (ChannelHandlerContext ctx, Object msg) {try {ByteBuf in = (ByteBuf) msg; System.out.println ("transmit content is"); System.out.println (in.toString (CharsetUtil.UTF_8)); ByteBuf resp= Unpooled.copiedBuffer ("receive message $" .getBytes ()); ctx.writeAndFlush (resp);} finally {ReferenceCountUtil.release (msg) } @ Override public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) throws Exception {/ / if there is an exception, close cause.printStackTrace (); ctx.close ();}}

Start the netty service

All right, we can start receiving data at this point.

Customer service end

1.TimeClient class

Public class TimeClient {public void connect (int port,String host) throws Exception {/ / configure client System.out.println (port+ "-" + host); EventLoopGroup eventLoopGroup=new NioEventLoopGroup (); try {Bootstrap b=new Bootstrap (); b.group (eventLoopGroup) .channel (NioSocketChannel.class) .option (ChannelOption.TCP_NODELAY,true) .handler (new ChannelInitializer () {protected void initChannel (SocketChannel socketChannel) throws Exception {socketChannel.pipeline (). AddLast (new TimeClientHandler ());}}) / / bind port, synchronously wait for successful ChannelFuture f = b.connect (host,port). Sync (); / wait for the service listening port to close f.channel (). CloseFuture (). Sync ();} finally {/ / graceful exit, releasing thread resources eventLoopGroup.shutdownGracefully ();}} public static void main (String [] args) throws Exception {new TimeClient (). Connect (8090, "localhost");}}

2.TimeClientHandler class

Public class TimeClientHandler extends ChannelHandlerAdapter {private byte [] req; public TimeClientHandler () {req= "$tmb00035ET3318/08/22 11req; public TimeClientHandler 5704026.75027.31 Magna 20.00" .getBytes ();} @ Override public void channelActive (ChannelHandlerContext ctx) throws Exception {ByteBuf message=null; for (int iTuno Tinci)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report