이전 기사를 작성했습니다. Java Network IO 프로그래밍 요약 (Bio, Nio 및 All All Complete Instance Code)으로 네트워크 프로그래밍에 Java 기본 IO 지원을 사용하는 방법을 소개합니다. 이 기사는 더 간단한 방법, 즉 Java Nio 프레임 워크를 소개합니다.
Netty는 업계에서 가장 인기있는 NIO 프레임 워크 중 하나이며 견고성, 기능, 성능, 커스터마이즈 및 확장 성이 뛰어납니다. 동시에 네트워크 프로그래밍을 크게 단순화하는 매우 간단한 API를 제공합니다.
Java IO가 소개 한 기사와 마찬가지로이 기사에 표시된 예제는 동일한 기능을 구현합니다.
1. 서버 측
섬기는 사람:
패키지 com.anxpp.io.calculator.netty; import io.netty.bootstrap.serverbootstrap; import io.netty.channel.channelfuture; import io.netty.channel.channelInitializer; 가져 오기 io.netty.channel.channelOption; import io.netty.channel.eventLoopGroup; import io.netty.channel.nio.nioeventLoopGroup; 가져 오기 io.netty.channel.socket.socketchannel; 가져 오기 io.netty.channel.socket.nio.nioserversocketchannel; 공개 클래스 서버 {private int port; 공개 서버 (int port) {this.port = 포트; } public void run ()은 예외를 던져 {eventLoopgroup bossgroup = new nioeventLoopgroup (); EventLoopGroup WorkerGroup = NEW NIOEVENTLOOPGROUP (); {serverbootstrap b = new ServerBootstrap (); B.group (BossGroup, WorkerGroup) .Channel (nioserversocketchanchann.class) .option (channelOption.so_backLog, 1024) .ChildOption (channelOption.so_keepalive, true) .ChildHandler (새로운 channelInitializer <socketchannel> () {@overrided public void initchannel (foodetchannel ch) throws throws retling {thowetchannel ch). ch.pipeline (). addLast (new ServerHandler ()); channelfuture f = b.bind (포트) .sync (); System.out.println ( "서버 :"+포트); f.channel (). CloseFuture (). sync (); } 마침내 {workerGroup.shutdownGracely (); bossgroup.shutdowngracely (); }} public static void main (String [] args)은 예외 {int port; if (args.length> 0) {port = integer.parseint (args [0]); } else {port = 9090; } 새 서버 (port) .run (); }}ServerHandler :
패키지 com.anxpp.io.calculator.netty; import io.netty.buffer.bytebuf; import io.netty.buffer.unpooled; import io.netty.channel.channel HandhandlerContext; import io.netty.channel.channelinboundhandleradapter; java.io.unsupportedencodingException 가져 오기; import com.anxpp.io.utils.calculator; Public Class ServerHandler 확장 channelInboundHandlerAdapter {@Override public void ChannelRead (channelHandlerContext CTX, Object Msg)는 unsupportedEncodingException {bytebuf in = (bytebuf) msg; 바이트 [] req = new Byte [in.ReadableBytes ()]; in.readBytes (req); 문자열 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 (Chann } / *** 예외 처리* / @override public void ExceptionCaught (Chann ctx.close (); }} 패키지 com.anxpp.io.calculator.netty; import io.netty.buffer.bytebuf; import io.netty.buffer.unpooled; import io.netty.channel.channel HandhandlerContext; import io.netty.channel.channelinboundhandleradapter; java.io.unsupportedencodingException 가져 오기; import com.anxpp.io.utils.calculator; Public Class ServerHandler 확장 channelInboundHandlerAdapter {@Override public void ChannelRead (channelHandlerContext CTX, Object Msg)는 unsupportedEncodingException {bytebuf in = (bytebuf) msg; 바이트 [] req = new Byte [in.ReadableBytes ()]; in.readBytes (req); 문자열 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 (Chann } / *** 예외 처리* / @override public void ExceptionCaught (Chann ctx.close (); }} 2. 클라이언트
고객:
패키지 com.anxpp.io.calculator.netty; import io.netty.bootstrap.bootstrap; import io.netty.channel.channelfuture; import io.netty.channel.channelInitializer; 가져 오기 io.netty.channel.channelOption; import io.netty.channel.eventLoopGroup; import io.netty.channel.nio.nioeventLoopGroup; 가져 오기 io.netty.channel.socket.socketchannel; 가져 오기 io.netty.channel.socket.nio.niosocketchannel; java.util.scanner import; 공개 클래스 클라이언트는 실행 가능 {static clientHandler 클라이언트 = new ClientHandler (); public static void main (string [] args)은 예외 {new Thread (new Client ()). start (); @SuppressWarnings ( "Resource") 스캐너 스캐너 = 새 스캐너 (System.In); while (client.sendmsg (scanner.nextline ()); } @override public void run () {문자열 host = "127.0.0.1"; int port = 9090; EventLoopGroup WorkerGroup = NEW NIOEVENTLOOPGROUP (); {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)은 예외를 {ch.pipeline (). addlast (client);}} 던지기; channelfuture f = b.connect (호스트, 포트) .sync (); f.channel (). CloseFuture (). sync (); } catch (InterruptedException e) {e.printstacktrace (); } 마침내 {workerGroup.shutdownGracely (); }}}ClientHandler :
패키지 com.anxpp.io.calculator.netty; import io.netty.buffer.bytebuf; import io.netty.buffer.unpooled; import io.netty.channel.channel HandhandlerContext; import io.netty.channel.channelinboundhandleradapter; java.io.unsupportedencodingException 가져 오기; Public Class ClientHandler 확장 channelInboundHandlerAdapter {ChannelHandlerContext CTX; / *** TCP 링크 이력서가 성공한 후 호출*/ @override public void channelActive (channelHandlerContext CTX)는 예외 {this.ctx = ctx; } public boolean sendmsg (String msg) {system.out.println ( "클라이언트 보내기 메시지 :"+msg); 바이트 [] req = msg.getBytes (); BYTEBUF M = Unpooled.buffer (req.length); M.WriteBytes (Req); Ctx.WriteAndFlush (M); 반환 msg.equals ( "Q")? false : true; } / *** 서버 메시지를받은 후 호출* @throws UnsupportedEncodingException* / @override public void Channelread (chant 바이트 [] req = new Byte [buf.readableBytes ()]; buf.readbytes (req); 문자열 body = new String (req, "utf-8"); System.out.println ( "서버 메시지 :"+body); } / *** 예외가 발생할 때 호출* / @override public void exceptionCaught (channelHandlerContext CTX, Throwable Cause) {CASE.PRINTSTACKTRACE (); ctx.close (); }} 3. 계산 도구
패키지 com.anxpp.io.utils; import javax.script.scripttengine; import javax.script.scripttengegenemanager; import javax.script.scriptexception; public enum calculator {instance; 개인 최종 정적 Scriptengine JSE = New ScriptengineManager (). getEngineByName ( "JavaScript"); public object cal (String expression)은 scriptexception {return jse.eval (expression); }} 4. 테스트
서버와 클라이언트를 각각 시작한 다음 클라이언트 콘솔에서 표현식을 입력하십시오.
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
서버에서 반환 한 결과를 볼 수 있습니다.
서버 콘솔보기 :
서버가 활성화되어 있습니다 : 9090 수신 된 클라이언트 메시지 : 1+5+5+5+5+5 수신 된 클라이언트 메시지 : 156158*458918+125615 수신 된 클라이언트 메시지 : 1895612+555+5+5+5+5+5+5+5+5+5+5+5-5*4/4
5. 더
관련 기사 :
Java Network IO 프로그래밍 요약 (Bio, Nio, AIO는 모두 완전한 인스턴스 코드를 포함합니다)
이 예제의 소스 코드 git 주소 및 Java Bio nio aio 예 : https://github.com/anxpp/java-io.git
간단한 통신 서버가 완료 될 때까지 Netty 관련 컨텐츠가 계속 업데이트됩니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.