In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to achieve the front end in Netty to send messages, the back end to receive messages and return", the article explains the content is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in-depth, together to study and learn "how to achieve front-end Netty to send messages, back-end to receive messages and return" bar!
1. Story traction
Today, we will explain netty through a story, mainly about the client and server side and the following main implementation classes.
Customers want to go to ktv to sing, before entering ktv, there will be a waiter at the door, and then when the waiter sees the customer, he will arrange for you to arrange a room for you by the ktv internal waiter, and then take you into the ktv room to sing. When you are ready to start singing, you should turn on the music, choose the song, turn on the lights and other factors. During this period, you may ask the singing waiter to help you sing. Let the dancing waiter dance for you, or even ask the waiter to bring you wine or food, until you finish singing and pay to leave, the whole process is over.
Proper nouns explain:
Client side: customer
Server side: ktv
MainGroup or boosGroup: the main thread group, which is equivalent to the waitress outside the door of ktv
SubGroup or workerGroup: the sub-thread group, which is equivalent to the ktv internal waiter, is responsible for arranging the room, and the waiter notifies the internal waiter to assign it to them.
ServerBootstrap: the whole process from before the customer enters ktv to after leaving ktv
HelloServerInitializer: the whole process after entering the ktv room
CustomHandler: respectively represents the functions of singing waiter, tea delivery waiter, dance waiter, etc.
1. NIO diagram
2. Server import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.Channel;import io.netty.channel.ChannelFuture;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioServerSocketChannel / * * @ Description: if the client sends a request, the server will return hello netty * / public class HelloServer {public static void main (String [] args) throws Exception {/ / define a pair of thread groups / / main thread groups to accept connections from the client, but do nothing, just like the boss, do nothing EventLoopGroup bossGroup = new NioEventLoopGroup () / / from the thread group, the boss thread group will throw the task to him and let his thread group do the task EventLoopGroup workerGroup = new NioEventLoopGroup (); try {/ / netty server creation, ServerBootstrap is a startup class ServerBootstrap serverBootstrap = new ServerBootstrap () ServerBootstrap.group (bossGroup, workerGroup) / / sets the master-slave thread group. channel (NioServerSocketChannel.class) / / sets the two-way channel for nio. ChildHandler (new HelloServerInitializer ()) / / subprocessor, which is used to process workerGroup / / boot server, and sets 8088 as the port number to boot, and the startup mode is synchronous ChannelFuture channelFuture = serverBootstrap.bind (8088). Sync (); / / listen for closed channel, set bit synchronization mode channelFuture.channel (). CloseFuture (). Sync ();} finally {bossGroup.shutdownGracefully () WorkerGroup.shutdownGracefully ();} 3, create processor import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.socket.SocketChannel;import io.netty.handler.codec.http.HttpServerCodec / * * @ Description: initializer. After channel registration, the corresponding initialization method * / public class HelloServerInitializer extends ChannelInitializer {@ Override protected void initChannel (SocketChannel channel) throws Exception {/ / get the corresponding pipeline ChannelPipeline pipeline = channel.pipeline () through SocketChannel / / through the pipeline, adding handler / / HttpServerCodec is a helper class provided by netty itself, which can be understood as interceptor / / when the request is sent to the server, we need to do decoding and respond to the client to do encoding pipeline.addLast ("HttpServerCodec", new HttpServerCodec ()) / / add a custom helper class and return "hello netty~" pipeline.addLast ("customHandler", new CustomHandler ());}} 4. Create helper class import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.Channel;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.handler.codec.http.DefaultFullHttpResponse;import io.netty.handler.codec.http.FullHttpResponse Import io.netty.handler.codec.http.HttpHeaderNames;import io.netty.handler.codec.http.HttpObject;import io.netty.handler.codec.http.HttpRequest;import io.netty.handler.codec.http.HttpResponseStatus;import io.netty.handler.codec.http.HttpVersion;import io.netty.util.CharsetUtil / * * @ Description: create a custom helper class * / SimpleChannelInboundHandler: for a request, it is actually equivalent to [inbound, inbound] public class CustomHandler extends SimpleChannelInboundHandler {@ Override protected void channelRead0 (ChannelHandlerContext ctx, HttpObject msg) throws Exception {/ / get channel Channel channel = ctx.channel () If (msg instanceof HttpRequest) {/ / display the remote address of the client System.out.println (channel.remoteAddress ()); / / define the data message sent ByteBuf content = Unpooled.copiedBuffer ("Hello netty~", CharsetUtil.UTF_8) / / build a http response FullHttpResponse response = new DefaultFullHttpResponse (HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content); / / add the data type and length to the response response.headers () .set (HttpHeaderNames.CONTENT_TYPE, "text/plain") Response.headers () .set (HttpHeaderNames.CONTENT_LENGTH, content.readableBytes ()); / / swipe the response to the client ctx.writeAndFlush (response);} @ Override public void channelRegistered (ChannelHandlerContext ctx) throws Exception {System.out.println ("channel.. Register "); super.channelRegistered (ctx);} @ Override public void channelUnregistered (ChannelHandlerContext ctx) throws Exception {System.out.println (" channel. Remove "); super.channelUnregistered (ctx);} @ Override public void channelActive (ChannelHandlerContext ctx) throws Exception {System.out.println (" channel. Active "); super.channelActive (ctx);} @ Override public void channelInactive (ChannelHandlerContext ctx) throws Exception {System.out.println (" channel. " Inactive "); super.channelInactive (ctx);} @ Override public void channelReadComplete (ChannelHandlerContext ctx) throws Exception {System.out.println (" channeld read completed. ") ; super.channelReadComplete (ctx);} @ Override public void userEventTriggered (ChannelHandlerContext ctx, Object evt) throws Exception {System.out.println ("user event triggered.") ; super.userEventTriggered (ctx, evt);} @ Override public void channelWritabilityChanged (ChannelHandlerContext ctx) throws Exception {System.out.println ("channel writable changes"); super.channelWritabilityChanged (ctx);} @ Override public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) throws Exception {System.out.println ("replenishment to exception"); super.exceptionCaught (ctx, cause) } @ Override public void handlerAdded (ChannelHandlerContext ctx) throws Exception {System.out.println ("helper class added"); super.handlerAdded (ctx);} @ Override public void handlerRemoved (ChannelHandlerContext ctx) throws Exception {System.out.println ("helper class removal"); super.handlerRemoved (ctx);}} 5, pom file io.netty netty-all 4.1.25.Final6, start main function
Open the browser: localhost:8088, the following error occurs, if you use the postman tool, you will find that there is no error, because the browser will close automatically.
Solution: just comment out super.exceptionCauht (ctx,case);
@ Overridepublic void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) throws Exception {/ / super.exceptionCaught (ctx, cause);}
Thank you for your reading, the above is the content of "how to send a message at the front end in Netty, the back end receives the message and returns". After the study of this article, I believe you have a deeper understanding of how to achieve the front end to send a message in Netty, and the back end receives the message and returns this question, the specific use situation also needs everybody to practice to verify. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.