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 use Netty to open UDP service in Springboot

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces how to use Netty to open UDP services in Springboot, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to understand it.

Netty

Netty is a tool to provide network programming, and it is an excellent packaging for socket programming. It supports TCP, UDP, FTP and other protocols. We can use Netty to develop our own http server, udp server, FTP server, RPC server, etc.

The reasons for the popularity of Netty are:

Concurrent high

Netty supports NIO programming, and the support of NIO can greatly improve concurrency performance.

Fast transmission

One of the features of Netty NIO is zero copy, which directly opens up a block in memory and leaves the socket buffer.

Seal it up

Next, write a simple udp demo. General ideas:

Write a netty UDP-based Server to accept data

Write a processing class to process the accepted data and then return the information

Create a new springboot project. Introducing jar into pom

Pom.xml

Org.springframework.boot spring-boot-starter 2.1.3.RELEASE org.springframework.boot spring-boot-starter-web io.netty netty-all org.projectlombok Lombok true creates NettyUDPServer

Type of Channel channel

NioSocketChannel, which represents asynchronous client-side TCP Socket connections.

NioServerSocketChannel, asynchronous server-side TCP Socket connection.

NioDatagramChannel, asynchronous UDP connection

NioSctpChannel, asynchronous client-side Sctp connection.

NioSctpServerChannel, asynchronous Sctp server-side connection.

OioSocketChannel, synchronous client TCP Socket connection.

OioServerSocketChannel, synchronous server-side TCP Socket connection.

OioDatagramChannel, synchronous UDP connection

OioSctpChannel, synchronous Sctp server-side connection.

OioSctpServerChannel, synchronous client TCP Socket connection.

Bootstrap is a convenient factory class provided by Netty that allows you to initialize Netty on the client or server side of Netty.

Package com.demo.udpdemo.UDPServer;import com.demo.udpdemo.handler.BootNettyUdpSimpleChannelInboundHandler;import io.netty.bootstrap.Bootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelOption;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioDatagramChannel;import lombok.extern.slf4j.Slf4j / * * @ author * / @ Slf4jpublic class BootNettyUdpServer {/ * start the service * / public void bind (int port) {log.info ("--udpServer-") / / indicates the server connection listening thread group, specially accepts accept's new client client connection EventLoopGroup bossLoopGroup = new NioEventLoopGroup (); try {/ / 1, creates the netty bootstrap startup class Bootstrap serverBootstrap = new Bootstrap (); / / 2, sets boostrap's eventLoopGroup thread group serverBootstrap = serverBootstrap.group (bossLoopGroup) / / 3. Set NIO UDP connection channel serverBootstrap = serverBootstrap.channel (NioDatagramChannel.class); / / 4, set channel parameters SO_BROADCAST broadcast form serverBootstrap = serverBootstrap.option (ChannelOption.SO_BROADCAST, true); / / 5, set processing class assembly line serverBootstrap = serverBootstrap.handler (new BootNettyUdpSimpleChannelInboundHandler ()) / / 6. Bind server and block asynchronously by calling the sync () method until ChannelFuture f = serverBootstrap.bind (port) .sync (); log.info (BootNettyUdpServer.class.getName () + "started and listend on" + f.channel () .localAddress ()) / / 7. Listen for the channel close event, and the application waits until channel closes f.channel (). CloseFuture (). Sync ();} catch (Exception e) {/ / TODO: handle exception} finally {System.out.println ("netty udp close!"); / / 8 close EventLoopGroup, bossLoopGroup.shutdownGracefully () } NettyUdpSimpleChannelInboundHandlerpackage com.demo.udpdemo.handler;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.channel.socket.DatagramPacket;import io.netty.util.CharsetUtil;import lombok.extern.slf4j.Slf4j / * @ author * / @ Slf4jpublic class BootNettyUdpSimpleChannelInboundHandler extends SimpleChannelInboundHandler {@ Override protected void channelRead0 (ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {try {String strdata = msg.content () .toString (CharsetUtil.UTF_8) / / print the received message log.info ("- receive data--"); log.info (strdata) Log.info ("- receive data--") / / after receiving the udp message, you can return the message by returning the message in this way, such as the return timestamp ctx.writeAndFlush (new DatagramPacket ("ok", CharsetUtil.UTF_8), msg.sender ()) } catch (Exception e) {}} modify the startup class, launch the UDPServer.bind method, launch udpServer@SpringBootApplication@EnableAsyncpublic class UdpDemoApplication implements CommandLineRunner {public static void main (String [] args) {SpringApplication app = new SpringApplication (UdpDemoApplication.class); app.run (args);} @ Async @ Override public void run (String...) Args) {new BootNettyUdpServer () .bind (51000);}} test

Under the test class, create a new test method

SendUdpRequestTest

/ / define client ip private static final String SERVER_HOSTNAME = "127.0.0.1"; / / Server port private static final int SERVER_PORT = 51000; / / Local send port private static final int LOCAL_PORT = 8888; @ Test public void sendUdpRequestTest () {try {/ / 1 to create a udp service. Through the DatagramSocket object. DatagramSocket socket = new DatagramSocket (LOCAL_PORT); / / 2, determine the data and encapsulate it into a packet. DatagramPacket (byte [] buf, int length, InetAddress / / address, int port) byte [] buf = "hello" .getBytes (); DatagramPacket dp = new DatagramPacket (buf, buf.length, InetAddress.getByName (SERVER_HOSTNAME), SERVER_PORT); / / 3, send existing packets through socket service. Through the send method. Socket.send (dp); / / 4, close the resource. Socket.close ();} catch (IOException e) {e.printStackTrace ();}} result

2021-09-03 13 INFO 14 receive data-- 47.912 Handler-[ntLoopGroup-2-1] .BootNettyUdpSimpleChannelInboundHandler:-BootNettyUdpSimpleChannelInboundHandler:-

2021-09-03 13 INFO 14 47.912 Handler-[ntLoopGroup-2-1] .BootNettyUdpSimpleChannelInboundHandler: Hello, World

2021-09-03 13 INFO 14 receive data-- 47.912 Handler-[ntLoopGroup-2-1] .BootNettyUdpSimpleChannelInboundHandler:-BootNettyUdpSimpleChannelInboundHandler:-

2021-09-03 13 INFO 16 11.748 Handler 11608-[ntLoopGroup-2-1] .BootNettyUdpSimpleChannelInboundHandler:-receive data--

2021-09-03 13 INFO 16 11.748 Handler-[ntLoopGroup-2-1] .BootNettyUdpSimpleChannelInboundHandler: Hello, World

2021-09-03 13 INFO 16 11.748 Handler 11608-[ntLoopGroup-2-1] .BootNettyUdpSimpleChannelInboundHandler:-receive data--

2021-09-03 13 INFO 1715 11.664 Handler-[ntLoopGroup-2-1] .BootNettyUdpSimpleChannelInboundHandler:-receive data--

2021-09-03 13 INFO 1715 11.664 Handler-[ntLoopGroup-2-1] .BootNettyUdpSimpleChannelInboundHandler: hello

2021-09-03 13 INFO 1715 11.664 Handler-[ntLoopGroup-2-1] .BootNettyUdpSimpleChannelInboundHandler:-receive data--

2021-09-03 13 receive data-- 17V 32.714 INFO 11608-[ntLoopGroup-2-1] .BootNettyUdpSimpleChannelInboundHandler:-BootNettyUdpSimpleChannelInboundHandler:-net

2021-09-03 13 INFO 1715 32. 714 Handler 11608-[ntLoopGroup-2-1] .BootNettyUdpSimpleChannelInboundHandler: hello

2021-09-03 13 receive data-- 17V 32.714 INFO 11608-[ntLoopGroup-2-1] .BootNettyUdpSimpleChannelInboundHandler:-BootNettyUdpSimpleChannelInboundHandler:-net

Thank you for reading this article carefully. I hope the article "how to use Netty to open UDP service in Springboot" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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