最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java NIO框架Netty簡(jiǎn)單使用的示例

 更新時(shí)間:2017年12月29日 13:43:57   作者:anxpp  
本篇文章主要介紹了Java NIO框架Netty簡(jiǎn)單使用的示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

之前寫了一篇文章:Java 網(wǎng)絡(luò)IO編程總結(jié)(BIO、NIO、AIO均含完整實(shí)例代碼),介紹了如何使用Java原生IO支持進(jìn)行網(wǎng)絡(luò)編程,本文介紹一種更為簡(jiǎn)單的方式,即Java NIO框架。

Netty是業(yè)界最流行的NIO框架之一,具有良好的健壯性、功能、性能、可定制性和可擴(kuò)展性。同時(shí),它提供的十分簡(jiǎn)單的API,大大簡(jiǎn)化了我們的網(wǎng)絡(luò)編程。

Java IO介紹的文章一樣,本文所展示的例子,實(shí)現(xiàn)了一個(gè)相同的功能。

1、服務(wù)端

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("服務(wù)器開啟:"+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("收到客戶端消息:"+body); 
    String calrResult = null; 
    try{ 
      calrResult = Calculator.Instance.cal(body).toString(); 
    }catch(Exception e){ 
      calrResult = "錯(cuò)誤的表達(dá)式:" + e.getMessage(); 
    } 
    ctx.write(Unpooled.copiedBuffer(calrResult.getBytes())); 
  } 
  @Override 
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 
    ctx.flush(); 
  } 
  /** 
   * 異常處理 
   */ 
  @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("收到客戶端消息:"+body); 
    String calrResult = null; 
    try{ 
      calrResult = Calculator.Instance.cal(body).toString(); 
    }catch(Exception e){ 
      calrResult = "錯(cuò)誤的表達(dá)式:" + e.getMessage(); 
    } 
    ctx.write(Unpooled.copiedBuffer(calrResult.getBytes())); 
  } 
  @Override 
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 
    ctx.flush(); 
  } 
  /** 
   * 異常處理 
   */ 
  @Override 
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 
    cause.printStackTrace(); 
    ctx.close(); 
  } 
} 

2、客戶端

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; 
  /** 
   * tcp鏈路簡(jiǎn)歷成功后調(diào)用 
   */ 
  @Override 
  public void channelActive(ChannelHandlerContext ctx) throws Exception { 
    this.ctx = ctx; 
  } 
  public boolean sendMsg(String msg){ 
    System.out.println("客戶端發(fā)送消息:"+msg); 
    byte[] req = msg.getBytes(); 
    ByteBuf m = Unpooled.buffer(req.length); 
    m.writeBytes(req); 
    ctx.writeAndFlush(m); 
    return msg.equals("q")?false:true; 
  } 
  /** 
   * 收到服務(wù)器消息后調(diào)用 
   * @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("服務(wù)器消息:"+body); 
  } 
  /** 
   * 發(fā)生異常時(shí)調(diào)用 
   */ 
  @Override 
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 
    cause.printStackTrace(); 
    ctx.close(); 
  } 
} 

3、用于計(jì)算的工具類

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、測(cè)試

分別啟動(dòng)服務(wù)端和客戶端,然后再客戶端控制臺(tái)輸入表達(dá)式:

1+5+5+5+5+5
客戶端發(fā)送消息:1+5+5+5+5+5
服務(wù)器消息:26
156158*458918+125615
客戶端發(fā)送消息:156158*458918+125615
服務(wù)器消息:7.1663842659E10
1895612+555+5+5+5+5+5+5+5-5*4/4
客戶端發(fā)送消息:1895612+555+5+5+5+5+5+5+5-5*4/4
服務(wù)器消息:1896197

可以看到服務(wù)端返回的結(jié)果。

查看服務(wù)端控制臺(tái):

服務(wù)器開啟:9090
收到客戶端消息:1+5+5+5+5+5
收到客戶端消息:156158*458918+125615
收到客戶端消息:1895612+555+5+5+5+5+5+5+5-5*4/4

5、更多

相關(guān)文章:

 Java 網(wǎng)絡(luò)IO編程總結(jié)(BIO、NIO、AIO均含完整實(shí)例代碼)

本文例子以及Java BIO NIO AIO例子的源碼Git地址:https://github.com/anxpp/Java-IO.git

后續(xù)會(huì)繼續(xù)更新Netty相關(guān)內(nèi)容,直到一個(gè)簡(jiǎn)陋的通訊服務(wù)器完成。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • JPA如何設(shè)置表名和實(shí)體名,表字段與實(shí)體字段的對(duì)應(yīng)

    JPA如何設(shè)置表名和實(shí)體名,表字段與實(shí)體字段的對(duì)應(yīng)

    這篇文章主要介紹了JPA如何設(shè)置表名和實(shí)體名,表字段與實(shí)體字段的對(duì)應(yīng),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • java 中死鎖問題的實(shí)例詳解

    java 中死鎖問題的實(shí)例詳解

    這篇文章主要介紹了java 中死鎖問題的實(shí)例詳解的相關(guān)資料,希望通過本文大家能夠理解掌握死鎖的問題,需要的朋友可以參考下
    2017-09-09
  • Java中Lambda表達(dá)式并行與組合行為

    Java中Lambda表達(dá)式并行與組合行為

    這篇文章主要介紹了Java中Lambda表達(dá)式并行與組合行為,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2017-02-02
  • JPA配置詳解之jpaProperties用法

    JPA配置詳解之jpaProperties用法

    這篇文章主要介紹了JPA配置詳解之jpaProperties用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • IDEA搭建純注解版本SpringMVC的web開發(fā)環(huán)境全過程并分析啟動(dòng)原理

    IDEA搭建純注解版本SpringMVC的web開發(fā)環(huán)境全過程并分析啟動(dòng)原理

    本文詳細(xì)介紹了如何使用注解開發(fā)搭建Spring Web環(huán)境,包括創(chuàng)建Maven工程、配置web環(huán)境、設(shè)置pom.xml、創(chuàng)建配置類和控制器等步驟,同時(shí),文章還探討了注解開發(fā)中如何創(chuàng)建IOC容器和添加DispatcherServlet組件,并通過Servlet 3.0規(guī)范
    2024-11-11
  • 詳解Spring Boot Oauth2緩存UserDetails到Ehcache

    詳解Spring Boot Oauth2緩存UserDetails到Ehcache

    這篇文章主要介紹了詳解Spring Boot Oauth2緩存UserDetails到Ehcache,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-08-08
  • 詳解如何在SpringBoot里使用SwaggerUI

    詳解如何在SpringBoot里使用SwaggerUI

    本篇文章主要介紹了詳解如何在SpringBoot里使用SwaggerUI,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-02-02
  • 使用spring框架實(shí)現(xiàn)數(shù)據(jù)庫事務(wù)處理方式

    使用spring框架實(shí)現(xiàn)數(shù)據(jù)庫事務(wù)處理方式

    這篇文章主要介紹了使用spring框架實(shí)現(xiàn)數(shù)據(jù)庫事務(wù)處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • 深入淺出MyBatis映射器

    深入淺出MyBatis映射器

    映射器是MyBatis最復(fù)雜也最重要的組件,也是基于MyBatis應(yīng)用程序開發(fā)中,本文主要介紹了深入淺出MyBatis映射器,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-04-04
  • RabbitMQ中的Channel和Exchange詳解

    RabbitMQ中的Channel和Exchange詳解

    這篇文章主要介紹了RabbitMQ中的Channel和Exchange詳解,創(chuàng)建和銷毀TCP連接很耗時(shí),打開太多TCP連接,耗操作系統(tǒng)資源,并發(fā)量大到一定程度,系統(tǒng)的吞吐量會(huì)降低,使用一個(gè)connection多channel的方式,可以提升連接的利用率,需要的朋友可以參考下
    2023-08-08

最新評(píng)論

唐山市| 营口市| 十堰市| 漳州市| 邯郸市| 宁海县| 金沙县| 沂南县| 土默特右旗| 黄冈市| 麻阳| 五莲县| 威信县| 贡嘎县| 溧水县| 桦甸市| 德令哈市| 慈溪市| 五常市| 抚松县| 石家庄市| 京山县| 泽州县| 新津县| 海林市| 灵寿县| 庆阳市| 军事| 九寨沟县| 阿拉善左旗| 山丹县| 西吉县| 祁连县| 鄂托克前旗| 曲麻莱县| 连州市| 兰西县| 柘荣县| 丰宁| 伊宁县| 宜春市|