一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|JavaScript|易語言|

服務(wù)器之家 - 編程語言 - JAVA教程 - Java NIO框架Netty簡單使用的示例

Java NIO框架Netty簡單使用的示例

2021-03-13 11:40anxpp JAVA教程

本篇文章主要介紹了Java NIO框架Netty簡單使用的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

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

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

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

1、服務(wù)端

Server:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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 = "錯誤的表達(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 = "錯誤的表達(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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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鏈路簡歷成功后調(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ā)生異常時調(diào)用
   */
  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    ctx.close();
  }
}

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

?
1
2
3
4
5
6
7
8
9
10
11
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、測試

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

?
1
2
3
4
5
6
7
8
9
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ù)端控制臺:

?
1
2
3
4
服務(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ù)會繼續(xù)更新Netty相關(guān)內(nèi)容,直到一個簡陋的通訊服務(wù)器完成。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:http://blog.csdn.net/anxpp/article/details/52108238

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 亚洲嫩模吧粉嫩粉嫩冒白浆 | 国产啪精品视频网给免丝袜 | 免费一区视频 | 消息称老熟妇乱视频一区二区 | 日韩一品在线播放视频一品免费 | 呜呜别塞了啊抽插 | 农村妇女野外牲交一级毛片 | 暖暖 免费 高清 中文 日本 | 久久青草费线频观看国产 | 欧美一级特黄刺激大片视频 | 亚洲国产剧情中文视频在线 | 国产小情侣自拍 | 天天做日日爱 | 被18号每天强行榨干acg | 鸭子玩富婆流白浆视频 | 美女福利视频一区二区 | 视频免费视频观看网站 | 欧美一级片在线视频 | 日本片免费观看一区二区 | 亚洲无线一二三区2021 | 2019天天干天天操 | 亚洲欧美国产自拍 | 亚洲福利电影一区二区? | 日韩在线第一区 | 蛮荒的童话未删减在线观看 | 岛国片免费观看 | 韩国最新三级网站在线播放 | 欧美图片另类小说综合 | 国产大乳美女挤奶视频 | 国产成人高清视频 | 国产caonila在线观看 | 女主被男主做哭失禁高h | 夫妇交换小说全文阅读 | 国产日韩精品一区二区在线观看 | gayrb免费漫画入口 | 国产精品九九久久一区hh | 久久国产伦子伦精品 | 午夜爱爱爱爱爽爽爽视频网站 | 免费观看在线 | 99r在线播放 | 四虎国产精品免费久久麻豆 |