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

An example of NettyClient semi-package sticky package processing code

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "NettyClient half-package sticky package processing code example". In daily operation, I believe that many people have doubts about NettyClient half-package sticky package processing code examples. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "NettyClient half-package sticky package processing code examples". Next, please follow the editor to study!

Introduction to the preface

In Netty development, the client and the server need to keep the same; half-packet sticky packet processing, encoding and decoding processing, sending and receiving data, so as to ensure normal data communication. We also dealt with it in the previous chapters of NettyServer; semi-sticky packets, coding and decoding, etc., so in this chapter we can develop these knowledge modules into NettyClient. The knowledge points involved in this chapter are LineBasedFrameDecoder, StringDecoder, StringEncoder, ChannelInboundHandlerAdapter and so on.

Development environment

1. Jdk1.8 [netty can only be partially supported below jdk1.7]

2. Netty4.1.36.Final [netty3.x 4.x 5 changes greatly each time, and the interface class name also changes]

3. Telnet test [you can test this command on your win7 machine now, which is used to link to the test command on the server]

Code sample itstack-demo-netty-1-08

└── src

├── main

│ └── java

│ └── org.itstack.demo.netty.client

│ ├── MyChannelInitializer.java

│ ├── MyClientHandler.java

│ └── NettyClient.java

└── test

└── java

└── org.itstack.demo.netty.test

└── ApiTest.java

MyChannelInitializer.java

/ * *

* wormhole stack: https://bugstack.cn

* official account: bugstack wormhole stack {get learning source code}

* Create by fuzhengwei on 2019

, /

Public class MyChannelInitializer extends ChannelInitializer {

@ Override

Protected void initChannel (SocketChannel channel) throws Exception {

/ / based on newline symbols

Channel.pipeline () .addLast (new LineBasedFrameDecoder (1024))

/ / Decoding to String, pay attention to adjust your own encoding format GBK, UTF-8

Channel.pipeline () .addLast (new StringDecoder (Charset.forName ("GBK"))

/ / Decoding to String, pay attention to adjust your own encoding format GBK, UTF-8

Channel.pipeline () .addLast (new StringEncoder (Charset.forName ("GBK"))

/ / add our own implementation method of receiving data to the pipeline

Channel.pipeline () .addLast (new MyClientHandler ()

}

}

MyClientHandler.java

/ * *

* wormhole stack: https://bugstack.cn

* official account: bugstack wormhole stack {get learning source code}

* Create by fuzhengwei on 2019

, /

Public class MyClientHandler extends ChannelInboundHandlerAdapter {

/ * *

* this channel becomes active when the client actively links the link on the server. That is, the client and the server establish a communication channel and can transmit data.

, /

@ Override

Public void channelActive (ChannelHandlerContext ctx) throws Exception {

SocketChannel channel = (SocketChannel) ctx.channel ()

System.out.println ("Link report start")

System.out.println ("Link report information: this client is linked to the server. ChannelId:" + channel.id ())

System.out.println ("linked report IP:" + channel.localAddress () .getHostString ())

System.out.println ("linked report Port:" + channel.localAddress () .getPort ())

System.out.println ("Link report completed")

/ / notify the client that the link has been established successfully

String str = "Notification server link established successfully" + "" + new Date () + "+ channel.localAddress () .getHostString () +"\ r\ n "

Ctx.writeAndFlush (str)

}

/ * *

* when the client actively disconnects the link from the server, this channel is inactive. That is to say, the communication channel between the client and the server is closed and the data cannot be transmitted.

, /

@ Override

Public void channelInactive (ChannelHandlerContext ctx) throws Exception {

System.out.println ("break link" + ctx.channel () .localAddress () .toString ())

}

@ Override

Public void channelRead (ChannelHandlerContext ctx, Object msg) throws Exception {

/ / receive msg messages {compared with the previous chapter, there is no need to decode it by yourself.

System.out.println (new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss") .format (new Date ()) + "received message:" + msg)

/ / notify the client chain that the message was sent successfully

String str = "client receives:" + new Date () + "" + msg + "\ r\ n"

Ctx.writeAndFlush (str)

}

/ * *

* catch the exception, and when an exception occurs, you can do some corresponding processing, such as printing the log and closing the link

, /

@ Override

Public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) throws Exception {

Ctx.close ()

System.out.println ("exception message:\ r\ n" + cause.getMessage ())

}

}

NettyClient.java

/ * *

* wormhole stack: https://bugstack.cn

* official account: bugstack wormhole stack {get learning source code}

* Create by fuzhengwei on 2019

, /

Public class NettyClient {

Public static void main (String [] args) {

New NettyClient () .connect ("127.0.0.1" 7397)

}

Private void connect (String inetHost, int inetPort) {

EventLoopGroup workerGroup = new NioEventLoopGroup ()

Try {

Bootstrap b = new Bootstrap ()

B.group (workerGroup)

B.channel (NioSocketChannel.class)

B.option (ChannelOption.AUTO_READ, true)

B.handler (new MyChannelInitializer ())

ChannelFuture f = b.connect (inetHost, inetPort). Sync ()

System.out.println ("itstack-demo-netty client start done. {follow official account: bugstack wormhole stack, get source code}")

F.channel (). CloseFuture (). Sync ()

} catch (InterruptedException e) {

E.printStackTrace ()

} finally {

WorkerGroup.shutdownGracefully ()

}

}

} Test results

Start the simulator NetAssist to set up TCP Server

Start the client NettyClient

Execution result

/ * *

* wormhole stack: https://bugstack.cn

* official account: bugstack wormhole stack {get learning source code}

* Create by fuzhengwei on 2019

, /

Public class NettyClient {

Public static void main (String [] args) {

New NettyClient () .connect ("127.0.0.1" 7397)

}

Private void connect (String inetHost, int inetPort) {

EventLoopGroup workerGroup = new NioEventLoopGroup ()

Try {

Bootstrap b = new Bootstrap ()

B.group (workerGroup)

B.channel (NioSocketChannel.class)

B.option (ChannelOption.AUTO_READ, true)

B.handler (new MyChannelInitializer ())

ChannelFuture f = b.connect (inetHost, inetPort). Sync ()

System.out.println ("itstack-demo-netty client start done. {follow official account: bugstack wormhole stack, get source code}")

F.channel (). CloseFuture (). Sync ()

} catch (InterruptedException e) {

E.printStackTrace ()

} finally {

WorkerGroup.shutdownGracefully ()

}

}

At this point, the study on the "NettyClient half-package sticky package processing code example" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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