以前に記事を書きました:Java Network IOプログラミングの概要(Bio、NIO、AIOにはすべて完全なインスタンスコードが含まれています)。これは、ネットワークプログラミングにJavaネイティブIOサポートの使用方法を紹介します。この記事では、よりシンプルな方法、つまりJava Nioフレームワークを紹介します。
Nettyは、業界で最も人気のあるNIOフレームワークの1つであり、堅牢性、機能性、パフォーマンス、カスタマイズ、スケーラビリティを備えています。同時に、ネットワークプログラミングを大幅に簡素化する非常にシンプルなAPIを提供します。
Java IOによって導入された記事のように、この記事に示されている例は同じ機能を実装しています。
1。サーバー側
サーバ:
パッケージcom.anxpp.io.calculator.netty; io.netty.bootstrap.serverbootstrapをインポートします。 io.netty.channel.channelfutureをインポートします。 IO.NETTY.CHANNEL.CHANNELINITIALIZERをインポートします。 io.netty.channel.channeloptionをインポートします。 io.netty.channel.eventloopgroupをインポートします。 io.netty.channel.nio.nioeventloopgroupをインポートします。 io.netty.channel.socket.socketchannelをインポートします。 io.netty.channel.socket.nio.nioserversocketchannelをインポートします。パブリッククラスサーバー{private int port; public server(int port){this.port = port; } public void run()スロー例外{eventloopgroup bossgroup = new nioeventloopgroup(); eventloopgroup workergroup = new nioeventloopgroup(); try {serverBootStrap b = new ServerBootStrap(); B.Group(BossGroup、WorkerGroup).Channel(nioserversocketchannel.class).option(channeloption.so_backlog、1024)。 ch.pipeline()。addlast(new ServerHandler()); Channelfuture f = b.bind(port).sync(); system.out.println( "server on:"+port); f.channel()。closefuture()。sync(); }最後に{workergroup.shutdowngracefuly(); BOSSGROUP.SHUTDOWNGRACELY(); }} public static void main(string [] args)throws exception {int port; if(args.length> 0){port = integer.parseint(args [0]); } else {port = 9090; } new Server(port).run(); }}サーバーハンドラー:
パッケージcom.anxpp.io.calculator.netty; io.netty.buffer.bytebufをインポートします。 io.netty.buffer.unpooledをインポートします。 io.netty.channel.channelhandlercontextをインポートします。 io.netty.channel.channelinboundhandleradapterをインポートします。 java.io.unsupportedencodingexceptionをインポートします。 com.anxpp.io.utils.calculatorをインポートします。 public class serverhandler拡張Channelinboundhandleradapter {@override public void channelwread(channelandlercontext ctx、object msg)throws unsupportedencodingexception {bytebuf in =(bytebuf)msg; byte [] req = new byte [in.readableBytes()]; in.readbytes(req); string body = new String(req、 "utf-8"); system.out.println( "クライアントメッセージ受信:"+body);文字列calrresult = null; try {calrresult = calculator.instance.cal(body).tostring(); } catch(例外e){calrresult = "エラー式:" + e.getmessage(); } ctx.write(unpooled.copiedbuffer(calrresult.getBytes())); } @Override public void ChannelReadComplete(ChannelHandlerContext CTX)スロー例外{ctx.flush(); } / ***例外処理* / @Override public void exceptioncaught(channelandlercontext ctx、throwable cause){cause.printstacktrace(); ctx.close(); }} package com.anxpp.io.calculator.netty; io.netty.buffer.bytebufをインポートします。 io.netty.buffer.unpooledをインポートします。 io.netty.channel.channelhandlercontextをインポートします。 io.netty.channel.channelinboundhandleradapterをインポートします。 java.io.unsupportedencodingexceptionをインポートします。 com.anxpp.io.utils.calculatorをインポートします。 public class serverhandler拡張Channelinboundhandleradapter {@override public void channelwread(channelandlercontext ctx、object msg)throws unsupportedencodingexception {bytebuf in =(bytebuf)msg; byte [] req = new byte [in.readableBytes()]; in.readbytes(req); string body = new String(req、 "utf-8"); system.out.println( "クライアントメッセージ受信:"+body);文字列calrresult = null; try {calrresult = calculator.instance.cal(body).tostring(); } catch(例外e){calrresult = "エラー式:" + e.getmessage(); } ctx.write(unpooled.copiedbuffer(calrresult.getBytes())); } @Override public void ChannelReadComplete(ChannelHandlerContext CTX)スロー例外{ctx.flush(); } / ***例外処理* / @Override public void exceptioncaught(channelandlercontext ctx、throwable cause){cause.printstacktrace(); ctx.close(); }} 2。クライアント
クライアント:
パッケージcom.anxpp.io.calculator.netty; io.netty.bootstrap.bootstrapをインポートします。 io.netty.channel.channelfutureをインポートします。 IO.NETTY.CHANNEL.CHANNELINITIALIZERをインポートします。 io.netty.channel.channeloptionをインポートします。 io.netty.channel.eventloopgroupをインポートします。 io.netty.channel.nio.nioeventloopgroupをインポートします。 io.netty.channel.socket.socketchannelをインポートします。 io.netty.channel.socket.nio.niosocketchannelをインポートします。 Java.util.scannerをインポートします。パブリッククラスクライアントはrunnable {static clienthandler client = new ClientHandler(); public static void main(string [] args)throws exception {newスレッド(new Client())。start(); @suppresswarnings( "resource")スキャナースキャナー= 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(); try {bootstrap b = new Bootstrap(); B.Group(WorkerGroup); B.Channel(niosocketchannel.class); b.option(channeloption.so_keepalive、true); b.handler(new ChannelInitializer <Socketchannel>(){@Override public void initchannel(socketchannel ch)throws exception {ch.pipeline()。addlast(client);}}}}); ChannelFuture f = b.connect(host、port).sync(); f.channel()。closefuture()。sync(); } catch(arturnedexception e){e.printstacktrace(); }最後に{workergroup.shutdowngracefuly(); }}}クライアントハンドラー:
パッケージcom.anxpp.io.calculator.netty; io.netty.buffer.bytebufをインポートします。 io.netty.buffer.unpooledをインポートします。 io.netty.channel.channelhandlercontextをインポートします。 io.netty.channel.channelinboundhandleradapterをインポートします。 java.io.unsupportedencodingexceptionをインポートします。 Public Class ClientHandlerは、ChannelinboundHandlerAdapterを拡張します{ChannelHandlerContext ctx; / *** TCPリンク履歴書が成功した後に呼び出されます*/ @Override public void channelactive(channelandlercontext ctx)スロー例外{this.ctx = ctx; } public boolean sendmsg(string msg){system.out.println( "クライアントはメッセージを送信します:"+msg); byte [] req = msg.getBytes(); bytebuf m = unpooled.buffer(req.length); M.WriteBytes(req); ctx.writeandflush(m); return msg.equals( "q")?false:true; } / ***サーバーメッセージを受信した後に呼び出されます* @throws unsupportedencodingexception* / @Override public void channelwread(channelandlercontext ctx、object msg)sulportedencodingexception {bytebuf buf =(bytebuf)msg; byte [] req = new byte [buf.readableBytes()]; buf.readbytes(req); string body = new String(req、 "utf-8"); System.out.println( "サーバーメッセージ:"+body); } / ***例外が発生したときに呼び出されます* / @Override public void exceptioncaught(channelandlercontext ctx、スロー可能な原因){cause.printstacktrace(); ctx.close(); }} 3。計算のためのツール
パッケージcom.ancpp.io.utils; Import javax.script.scriptengine; Import javax.script.scriptenginemanager; Import javax.script.scriptexception; public enum calculator {instance; private final static scriptengine jse = new ScriptEngineManager()。getEngineByName( "JavaScript"); public Object cal(string expression)throws scriptexception {return jse.eval(expression); }} 4。テスト
それぞれサーバーとクライアントを起動し、クライアントコンソールに式を入力します。
1+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+5-5*4/4/4/4
サーバーによって返された結果を見ることができます。
サーバーコンソールを表示します:
サーバーが有効になっています:9090受信クライアントメッセージ:1+5+5+5+5+5受信クライアントメッセージ:156158*458918+125615クライアントメッセージ:1895612+555+5+5+5+5+5+5+5+5+5+5+5+5-5*4/4/4/4
5。もっと
関連記事:
Java Network IOプログラミングの概要(Bio、NIO、AIOにはすべて完全なインスタンスコードが含まれています)
この例のソースコードgitアドレスとJava bio nio aioの例:https://github.com/anxpp/java-io.git
ネット関連のコンテンツは、単純な通信サーバーが完了するまで更新され続けます。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。