J'ai déjà écrit un article: Java Network IO Programming Résumé (BIO, NIO et AIO contiennent tous du code d'instance complet), qui présente comment utiliser la prise en charge d'IO native Java pour la programmation réseau. Cet article présente une méthode plus simple, à savoir le framework Java Nio.
Netty est l'un des cadres NIO les plus populaires de l'industrie, avec une bonne robustesse, une fonctionnalité, des performances, une personnalisation et une évolutivité. Dans le même temps, il fournit une API très simple qui simplifie considérablement notre programmation réseau.
Comme l'article introduit par Java IO, les exemples indiqués dans cet article implémentent la même fonction.
1. Côté serveur
Serveur:
package com.anxpp.io.calculator.netty; import io.netty.bootstrap.serverbootstrap; import io.netty.channel.chanfuture; import io.netty.channel.channelinitializer; import io.netty.channel.channeloption; import io.netty.channel.eventloopgroup; import io.netty.channel.nio.nioeventloopgroup; import io.netty.channel.socket.socketchannel; import io.netty.channel.socket.nio.nioserversocketchannel; Public Class Server {Private int port; Server public (port int) {this.port = port; } public void run () lève une exception {eventLoopGroup bossGroup = new NioEventLoopGroup (); EventLoopGroup WorkerGroup = new NioEventLoopGroup (); essayez {serverbootstrap b = new serverbootstrap (); B.Group (BossGroup, WorkerGroup) .Channel (NioserVersocketchannel.class) .option (ChannelOption.SO_BACKLOG, 1024) .ChildOption (ChannelOption.SO_KENEYLIVE, True) .ChildHandler (New ChannelInitializer <Socketchannel> () {@Override Public Void INitchannell (SOCKetchannel Ch) Throws Except {Gublic Void INitchannell (SOCKetchannel Ch) Throws Except {Gublic Void INitchannell (SOCKetchannel Ch) Throws Except {Gublic Void INitchannell (SOCKetchannel Ch) Throws Except {Override Public Void Initchannell (Socketchannel CH) ch.pipeline (). addLast (new serverHandler ());}}); Channelfuture f = B.Bind (port) .Sync (); System.out.println ("Server sur:" + port); F.Channel (). CloseFuture (). Sync (); } enfin {workerGroup.shutdowngracely (); bossgroup.shutdowngracely (); }} public static void main (String [] args) lève l'exception {int port; if (args.length> 0) {port = Integer.Parseint (args [0]); } else {port = 9090; } nouveau serveur (port) .run (); }}ServerHandler:
package com.anxpp.io.calculator.netty; import io.netty.buffer.bytebuf; import io.netty.buffer.unpooled; import io.netty.channel.channelHandlerContext; import io.netty.channel.channelinboundhandleradapter; Importer java.io.UNSUPPORTEDENCODINGException; import com.anxpp.io.utils.calculateur; La classe publique ServerHandler étend ChannelInboundHandlerAdapter {@Override public void ChannelRead (ChannelHandlerContext CTX, objet msg) lève unportEDenCcodingException {bytebuf dans = (bytebuf) msg; octet [] req = new byte [in.readableBytes ()]; in.readbytes (req); String body = new String (req, "utf-8"); System.out.println ("Message client reçu:" + corps); String calrresult = null; essayez {calrresult = calculator.instance.cal (body) .toString (); } catch (exception e) {calrresult = "Error Expression:" + e.getMessage (); } ctx.write (nonool.copiedBuffer (calrresult.getbytes ())); } @Override public void ChannelReadComplete (ChannelHandlerContext ctx) lève l'exception {ctx.flush (); } / ** * Gestion des exceptions * / @Override public void exceptioncaught (ChannelHandlerContext ctx, cause throwable) {cause.printStackTrace (); ctx.close (); }} package com.anxpp.io.calculator.netty; import io.netty.buffer.bytebuf; import io.netty.buffer.unpooled; import io.netty.channel.channelHandlerContext; import io.netty.channel.channelinboundhandleradapter; Importer java.io.UNSUPPORTEDENCODINGException; import com.anxpp.io.utils.calculateur; La classe publique ServerHandler étend ChannelInboundHandlerAdapter {@Override public void ChannelRead (ChannelHandlerContext CTX, objet msg) lève unportEDenCcodingException {bytebuf dans = (bytebuf) msg; octet [] req = new byte [in.readableBytes ()]; in.readbytes (req); String body = new String (req, "utf-8"); System.out.println ("Message client reçu:" + corps); String calrresult = null; essayez {calrresult = calculator.instance.cal (body) .toString (); } catch (exception e) {calrresult = "Error Expression:" + e.getMessage (); } ctx.write (nonool.copiedBuffer (calrresult.getbytes ())); } @Override public void ChannelReadComplete (ChannelHandlerContext ctx) lève l'exception {ctx.flush (); } / ** * Gestion des exceptions * / @Override public void exceptioncaught (ChannelHandlerContext ctx, cause throwable) {cause.printStackTrace (); ctx.close (); }} 2. Client
Client:
package com.anxpp.io.calculator.netty; import io.netty.bootstrap.bootstrap; import io.netty.channel.chanfuture; import io.netty.channel.channelinitializer; import io.netty.channel.channeloption; import io.netty.channel.eventloopgroup; import io.netty.channel.nio.nioeventloopgroup; import io.netty.channel.socket.socketchannel; import io.netty.channel.socket.nio.niosocketchannel; import java.util.scanner; CLASSE PUBLIC CLIENT IMPLIMENTATION RANNABLE {static clientHandler client = new ClientHandler (); public static void main (String [] args) lève une exception {nouveau thread (new client ()). start (); @SuppressWarnings ("Resource") Scanner Scanner = new Scanner (System.in); while (client.sendmsg (Scanner.NextLine ())); } @Override public void run () {String host = "127.0.0.1"; int port = 9090; EventLoopGroup WorkerGroup = new NioEventLoopGroup (); essayez {bootstrap b = new bootstrap (); B.Group (WorkerGroup); B.Channel (niosocketchannel.class); b.option (canalOption.so_keepalive, true); B.Handler (new ChannelInitializer <Socketchannel> () {@Override public void initchannel (socketchannel ch) lève une exception {ch.pipeline (). addLast (client);}}); Channelfuture f = b.connect (hôte, port) .Sync (); F.Channel (). CloseFuture (). Sync (); } catch (InterruptedException e) {e.printStackTrace (); } enfin {workerGroup.shutdowngracely (); }}}ClientHandler:
package com.anxpp.io.calculator.netty; import io.netty.buffer.bytebuf; import io.netty.buffer.unpooled; import io.netty.channel.channelHandlerContext; import io.netty.channel.channelinboundhandleradapter; Importer java.io.UNSUPPORTEDENCODINGException; classe publique ClientHandler étend ChannelInboundHandlerAdapter {ChannelHandlerContext CTX; / ** * Appelé après le lien TCP, le CV est réussi * / @Override public void ChannelActive (ChannelHandlerContext ctx) lève exception {this.ctx = ctx; } public boolean sendmsg (String msg) {System.out.println ("Le client envoie le message:" + msg); byte [] req = msg.getBytes (); Bytebuf m = nonoled.buffer (req.length); M.WriteBytes (req); ctx.writeAndflush (m); return msg.equals ("q")? false: true; } / ** * Appelé après avoir reçu le message du serveur * @Throws UnsupportDenCcodingException * / @Override public void ChannelRead (ChannelHandlerContext CTX, Object Msg) lance unpptedEncodException {ByteBuf buf = (bytebuf) msg; octet [] req = new byte [buf.readableBytes ()]; buf.readbytes (req); String body = new String (req, "utf-8"); System.out.println ("Message du serveur:" + corps); } / ** * Appelé lorsqu'une exception se produit * / @Override public void exceptioncaught (ChannelHandlerContext CTX, Cause thrownable) {Cause.printStackTrace (); ctx.close (); }} 3. Outils de calcul
package com.anxpp.io.utils; import javax.script.scriptengine; import javax.script.scriptenGineManager; import javax.script.scriptException; publication de calculatrice d'énumération {instance; private final static scriptengine jse = new ScriptenMineManager (). getEngineByName ("javascript"); L'objet public CAL (Expression de chaîne) lève ScripTException {return jSe.eval (expression); }} 4. Test
Démarrez respectivement le serveur et le client, puis entrez l'expression sur la console client:
1 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 * 4/4/4/4/5/5/5 / 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5-5 * 4/4/4
Vous pouvez voir les résultats renvoyés par le serveur.
Afficher la console du serveur:
Le serveur est activé: 9090 Message client reçu: 1 + 5 + 5 + 5 + 5 + 5 Message client reçu: 156158 * 458918 + 125615 Message du client reçu: 1895612 + 555 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5-5 * 4/4
5. Plus
Articles connexes:
Résumé de la programmation Java Network IO (Bio, Nio, AIO contiennent tous du code d'instance complet)
L'adresse du code source de cet exemple et Java Bio Nio AIO Exemple: https://github.com/anxpp/java-io.git
Le contenu lié à Netty continuera d'être mis à jour jusqu'à la fin d'un serveur de communication simple.
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.