In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 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 function of Netty". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to achieve the function of Netty".
Netty is the framework that was first learned at the beginning of the year. The recent book rental system wants to use the chat function to achieve one-to-one dialogue chat. When the user logs in to the server, the user ip is bound to id and put into the channelgroup. Each cycle traverses the corresponding channel of the ip, otherwise, the false is returned, and the online status belongs to the handler message function.
1. One-on-one chat
two。 Show the number of people online
3. Login authentication
4. Input box optimization
5. Can support expression
Long live open source
When looking for the implementation of Netty one-to-one chat function, in addition to reviewing the function points, you can also find something new, a small demo, but others do not do so, refined to verification, but also take into account the performance, take a look at the implementation effect page
Nickname input is required. After login, it is not a simple addition of data.
Private static ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock (true); private static ConcurrentMap userInfos = new ConcurrentHashMap (); private static AtomicInteger userCount = new AtomicInteger (0)
Read-write lock
Concurrent packet
Atomic counting
Because the online statistics of users are finally realized, atomic AtomicInteger is used.
Private static AtomicInteger uidGener = new AtomicInteger (1000)
Private boolean isAuth = false; / / whether to authenticate private long time = 0; / / login time private int userId; / / UID private String nick; / / nickname private String addr; / / address private Channel channel;// channel
Log in to the user information, determine the nickname, get the ip, and put each user ip,channel into the channelGroup one by one.
How do I send a message?
In message processing Handler, override the channelread0 method
1. Gets whether the channel of this user information exists
two。 There is a broadcast of user id, nickname, and received messages to the page for display.
3. Message is not null, read-write lock is added, and the current user's channel is found.
4. Traverses the user information and returns it through the netty write callback
If (msg instanceof FullHttpRequest) {handleHttpRequest (ctx, (FullHttpRequest) msg);} else if (msg instanceof WebSocketFrame) {handleWebSocket (ctx, (WebSocketFrame) msg);}
Connect Handler acceptance to Server
1. Timed shutdown of failed channel
two。 Regularly send ping messages to the client
Message processing flow of Netty
Define the parent-child thread group-> define the relevant processing channel processor in childInitializer-- > provide your own processor in the callback
Now start the callback.
.childHandler (new ChannelInitializer () {
@ Override protected void initChannel (SocketChannel ch) throws Exception {put group into the message pipeline ch.pipeline () .addLast (defLoopGroup, / / request decoder new HttpServerCodec () / / convert multiple messages into a single message object new HttpObjectAggregator (65536), / / support sending large code streams asynchronously Generally used to send file stream new ChunkedWriteHandler (), / / detect whether the link reads idle new IdleStateHandler (60,0,0), / / handle handshake and authentication new UserAuthHandler () / / send new MessageHandler for processing messages () })
Regular processing of failure messages
/ / scan all Channel regularly and close the failed Channel executorService.scheduleAtFixedRate (new Runnable () {@ Override public void run () {logger.info ("scanNotActiveChannel -"); UserInfoManager.scanNotActiveChannel ();}}, 3,60, TimeUnit.SECONDS)
/ / regularly send Ping messages executorService.scheduleAtFixedRate (new Runnable () {@ Override public void run () {UserInfoManager.broadCastPing ();}}, 3,50, TimeUnit.SECONDS) to all clients.
The front-end page hasn't changed much.
1. Bind websocket
2.websocket calls onmessage to process messages
Window.socket = new WebSocket ("ws://localhost:9688/websocket")
Processing technology:
1. Thread pool
2.Lambad expression
3. Read-write locks improve performance
4. Atomic reference ensures atomicity and thread safety
Debug
The user logs in to determine whether it is a given message type
Get nickname, user information, code
= = success, save user information
Do not log in for the first time without this user id and channel, do not broadcast messages
User count 0 broadCastPing userCount: 0
When sending a message to the page
Trigger a scheduled message broadcast to traverse the size
Processing message ctx.fireChannelRead (frame.retain ())
At this time, broadcast user count broadCastPing userCount: 1
Websocket realizes a real long connection between the client and the server, saving bandwidth and focusing on the content itself.
Websocket:1--: bidirectional data transfer
2Murray: based on Http
3Murray: non-browser situations
Thank you for your reading, the above is the content of "how to achieve Netty function", after the study of this article, I believe you have a deeper understanding of how to achieve Netty function, and the specific use needs to be verified in practice. 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.