I wrote an article before: Java Network IO Programming Summary (BIO, NIO, and AIO all contain complete instance code), which introduces how to use Java native IO support for network programming. This article introduces a simpler method, namely the Java NIO framework.
Netty is one of the most popular NIO frameworks in the industry, with good robustness, functionality, performance, customization and scalability. At the same time, it provides a very simple API that greatly simplifies our network programming.
Like the article introduced by Java IO, the examples shown in this article implement the same function.
1. Server side
Server:
package com.anxpp.io.calculator.netty; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; 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; public Server(int port) { this.port = port; } public void run() throws Exception { 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) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ServerHandler()); } }); ChannelFuture f = b.bind(port).sync(); System.out.println("Server on:"+port); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } 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(); } }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; import java.io.UnsupportedEncodingException; import com.anxpp.io.utils.Calculator; public class ServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext 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("Client message received:"+body); String calrResult = null; try{ calrResult = Calculator.Instance.cal(body).toString(); }catch(Exception e){ calrResult = "Error expression: " + e.getMessage(); } ctx.write(Unpooled.copiedBuffer(calrResult.getBytes())); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } /** * Exception handling*/ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 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; import java.io.UnsupportedEncodingException; import com.anxpp.io.utils.Calculator; public class ServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext 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("Client message received:"+body); String calrResult = null; try{ calrResult = Calculator.Instance.cal(body).toString(); }catch(Exception e){ calrResult = "Error expression: " + e.getMessage(); } ctx.write(Unpooled.copiedBuffer(calrResult.getBytes())); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } /** * Exception handling*/ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } 2. Client
Client:
package com.anxpp.io.calculator.netty; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; 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; public class Client implements Runnable{ static ClientHandler client = new ClientHandler(); public static void main(String[] args) throws Exception { new 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(); 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 (InterruptedException e) { e.printStackTrace(); } finally { workerGroup.shutdownGracefully(); } } }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; import java.io.UnsupportedEncodingException; public class ClientHandler extends ChannelInboundHandlerAdapter { ChannelHandlerContext ctx; /** * Called after the tcp link resume is successful*/ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; } public boolean sendMsg(String msg){ System.out.println("Client sends message: "+msg); byte[] req = msg.getBytes(); ByteBuf m = Unpooled.buffer(req.length); m.writeBytes(req); ctx.writeAndFlush(m); return msg.equals("q")?false:true; } /** * Called after receiving the server message* @throws UnsupportedEncodingException */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException { ByteBuf buf = (ByteBuf) msg; byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String body = new String(req,"utf-8"); System.out.println("Server message: "+body); } /** * Called when an exception occurs*/ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } 3. Tools for calculation
package com.anxpp.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. Test
Start the server and client respectively, and then enter the expression on the client console:
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-5*4/4/4
You can see the results returned by the server.
View the server console:
Server is enabled: 9090 Received client message: 1+5+5+5+5+5 Received client message: 156158*458918+125615 Received client message: 1895612+555+5+5+5+5+5+5+5+5+5+5-5*4/4
5. More
Related articles:
Java network IO programming summary (BIO, NIO, AIO all contain complete instance code)
The source code Git address of this example and Java BIO NIO AIO example: https://github.com/anxpp/Java-IO.git
Netty related content will continue to be updated until a simple communication server is completed.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.