欢马劈雪     最近更新时间:2020-01-02 10:19:05

408
非阻塞套接字通道回显服务器程序

import java.io.IOException;

import java.net.InetAddress;//来 自 NowJava.com - 时  代  Java

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.CharBuffer;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.nio.charset.Charset;

import java.nio.charset.CharsetDecoder;

import java.util.Iterator;

import java.util.Set;


public class Main {

  public static void main(String[] args) throws Exception {

    InetAddress hostIPAddress = InetAddress.getByName("localhost");

    int port = 19000;


    Selector selector = Selector.open();/*nowjava.com - 时  代  Java 提 供*/


    ServerSocketChannel ssChannel = ServerSocketChannel.open();


    ssChannel.configureBlocking(false);

    ssChannel.socket().bind(new InetSocketAddress(hostIPAddress, port));


    ssChannel.register(selector, SelectionKey.OP_ACCEPT);


    while (true) {

      if (selector.select() <= 0) {

        continue;

      }

      processReadySet(selector.selectedKeys());

    }

  }


  public static void processReadySet(Set readySet) throws Exception {

    SelectionKey key = null;

    Iterator iterator = null;

    iterator = readySet.iterator();

    while (iterator.hasNext()) {

      key = (SelectionKey) iterator.next();

      iterator.remove();

      if (key.isAcceptable()) {

        processAccept(key);

      }


      if (key.isReadable()) {

        String msg = processRead(key);

        if (msg.length() > 0) {

          echoMsg(key, msg);

        }

      }

    }

  }


  public static void processAccept(SelectionKey key) throws IOException {

    ServerSocketChannel ssChannel =  (ServerSocketChannel)key.channel();

    SocketChannel sChannel = (SocketChannel) ssChannel.accept();

    sChannel.configureBlocking(false);

    sChannel.register(key.selector(), SelectionKey.OP_READ);

  }


  public static String processRead(SelectionKey key) throws Exception {

    SocketChannel sChannel = (SocketChannel) key.channel();

    ByteBuffer buffer = ByteBuffer.allocate(1024);

    int bytesCount = sChannel.read(buffer);

    String msg = "";


    if (bytesCount > 0) {

      buffer.flip();

      Charset charset = Charset.forName("UTF-8");

      
展开阅读全文