NIO的服务端客户端DEMO

服务端代码:

package cn.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * NIO服务端
 * 
 */
public class NIOServer implements Runnable {

  // 通道管理器
  private Selector selector;
  private ByteBuffer readBuffer = ByteBuffer.allocate(1024);
  private ByteBuffer writeBuffer = ByteBuffer.allocate(1024);


  public NIOServer(int port) {
    init(port);
  }

  /**
   * 获得一个ServerSocket通道,并对该通道做一些初始化的工作
   * 
   * @param port 绑定的端口号
   */
  public void initServer(int port) throws IOException {
    init(port);
  }

  private void init(int port) {
    try {
      System.out.println("Server staring at port: " + port);
      // 开启多路复用器
      this.selector = Selector.open();
      // 开启服务通道
      ServerSocketChannel serverChannel = ServerSocketChannel.open();
      serverChannel.configureBlocking(false);
      serverChannel.bind(new InetSocketAddress(port));
      serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
      System.out.println("Server started");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
   * 
   */
  public void run() {
    while (true) {
      try {
        this.selector.select();
        Iterator<SelectionKey> keys = this.selector.selectedKeys().iterator();
        while (keys.hasNext()) {
          SelectionKey key = keys.next();
          keys.remove();
          if (key.isValid()) {
            try {
              if (key.isAcceptable()) {
                accept(key);
              }
            } catch (CancelledKeyException cke) {
              key.cancel();
            }
            try {
              if (key.isReadable()) {
                read(key);
              }
            } catch (CancelledKeyException cke) {
              key.cancel();
            }
            try {
              if (key.isWritable()) {
                write(key);
              }
            } catch (CancelledKeyException cke) {
              key.cancel();
            }
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  private void accept(SelectionKey key) {
    try {
      ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
      SocketChannel channel = serverChannel.accept();
      channel.configureBlocking(false);
      channel.register(this.selector, SelectionKey.OP_READ);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private void read(SelectionKey key) {
    try {
      this.readBuffer.clear();
      SocketChannel channel = (SocketChannel) key.channel();
      int readLength = channel.read(readBuffer);
      if (readLength == -1) {
        key.channel().close();
        key.cancel();
        return;
      }
      this.readBuffer.flip();
      byte[] datas = new byte[readBuffer.remaining()];
      readBuffer.get(datas);
      System.out
          .println("From " + channel.getRemoteAddress() + "Clinet: " + new String(datas, "UTF-8"));
      channel.register(this.selector, SelectionKey.OP_WRITE);
    } catch (IOException e) {
      e.printStackTrace();

    }
  }

  @SuppressWarnings("resource")
  private void write(SelectionKey key) {
    this.writeBuffer.clear();
    SocketChannel channel = (SocketChannel) key.channel();
    Scanner reader = new Scanner(System.in);
    try {
      String line = reader.nextLine();
      writeBuffer.put(line.getBytes("UTF-8"));
      writeBuffer.flip();
      channel.write(writeBuffer);
      channel.register(this.selector, SelectionKey.OP_READ);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 启动服务端测试
   * 
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {
    new Thread(new NIOServer(9999)).start();
  }

}

客户端代码:

package cn.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * NIO客户端
 * 
 * @author 小路
 */
public class NIOClient {

  /**
   * 启动客户端测试
   * 
   */
  @SuppressWarnings("resource")
  public static void main(String[] args) throws IOException {
    InetSocketAddress remote = new InetSocketAddress("localhost", 9999);
    SocketChannel channel = null;
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    try {
      channel = SocketChannel.open();
      channel.connect(remote);
      Scanner reader = new Scanner(System.in);
      while (true) {
        System.out.println("Put message send to server>");
        String line = reader.nextLine();
        if (line.equals("exit")) {
          break;
        }
        buffer.put(line.getBytes("UTF-8"));
        buffer.flip();
        channel.write(buffer);
        buffer.clear();

        int readLength = channel.read(buffer);
        if (readLength == -1) {
          break;
        }
        buffer.flip();
        byte[] datas = new byte[buffer.remaining()];
        buffer.get(datas);
        System.out.println("From server " + new String(datas, "UTF-8"));
        buffer.clear();
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (null != channel) {
        channel.close();
      }
    }
  }
}

先启动server 再启动client 就能数据互通了

  • client console:


    image.png
  • server console:


    image.png
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,423评论 19赞 139
  • 关于Mongodb的全面总结 MongoDB的内部构造《MongoDB The Definitive Guide》...
    中v中阅读 32,560评论 2赞 89
  • 是应勤。对,就是这个固执的,让邱莹莹歇斯底里,第二次疯魔的青年。 为什么这么说?因为他的处女情结。接下来的讨论,没...
    花生龟阅读 373评论 0赞 2
  • 你不主动和我说话 主动远离我 主动疏远我 聪明的人应该知道 这是停止的意思 哪怕在那唯一的地方 路的远近决定于自己...
    爱纠结墨迹的人阅读 456评论 0赞 0
  • 说起人和,可能很多人都已经忘了这个名字,谁还记得这个发家于黑龙江哈尔滨,开创地产新模式,巅峰时期叫板恒大,人称“防...
    蜡笔小幸阅读 6,823评论 1赞 4

友情链接更多精彩内容