Java IO多路复用技术简介(2)

/**
    * 向指定的SocketChannel发送指定的消息。
    *
    * @param sc      需要向哪一个SocketChannel发送消息
    * @param content 需要发送的消息
    * @throws Exception
    */
    private void doWrite(SocketChannel sc, String content) throws Exception {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put(content.getBytes("UTF-8"));
        buffer.flip();
        sc.write(buffer);
        if (!buffer.hasRemaining()) {
            System.out.println("下发消息给客户端:" + content);
        }
    }
}

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @author qifuguang
 * @date 15-2-4 下午1:21
 */
public class SelectorTimeClient implements Runnable {
    private static final String TIME_ORDER = "Query Time";
    private SocketChannel channel;
    private Selector selector;
    private volatile boolean stop = false;
    private Integer index;

/**
    * 创建Selector, SocketChannel.
    *
    * @param index 客户端编号.
    * @throws Exception
    */
    public SelectorTimeClient(Integer index) throws Exception {
        selector = Selector.open();
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        this.index = index;
    }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/8d4ecd5ba8b62a53f2b9ad15127ee7f5.html