NIO发送消息简单的例子

版权声明:本文为博主原创文章,未经博主允许不得转载!!! https://blog.csdn.net/qq_19107011/article/details/80802258

服务端代码

package miv.study;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectableChannel;
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.Set;

public class Server {
    public static void main(String[] args) throws Exception {
        server();
    }

    public static void server() throws Exception {
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        serverChannel.socket().bind(new InetSocketAddress(2323));
        Selector selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            int n = selector.select();
            if (n == 0)
                continue;
            Iterator ite = selector.selectedKeys().iterator();
            while (ite.hasNext()) {
                SelectionKey key = (SelectionKey) ite.next();
                if (key.isAcceptable()) {
                    SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept();
                    clntChan.configureBlocking(false);
                    clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()) {
                    handleRead(key);
                }
                if (key.isWritable() && key.isValid()) {
                    handleWrite(key);
                }
                if (key.isConnectable()) {
                    System.out.println("isConnectable = true");
                }
                ite.remove();
            }
        }

    }

    private static void handleRead(SelectionKey key) throws Exception {
        SocketChannel inChannel = (SocketChannel) key.channel();

        ByteBuffer buf = ByteBuffer.allocate(48);

        int bytesRead = inChannel.read(buf);
        while (bytesRead != -1) {

            buf.flip();// 记录读取到的最后位置,重第0,开始获取

            while (buf.hasRemaining()) {
                System.out.print((char) buf.get());
            }
            buf.clear();// 重置缓存区
            bytesRead = inChannel.read(buf);
        }
        inChannel.close();
    }

    private static void handleWrite(SelectionKey key) {
        System.out.println("handleWrite");
    }

}

客户端代码

package miv.study;

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

public class Client {
    public static void main(String[] args) throws Exception {
        client();
    }
    //客户端
    public static void client()throws Exception{
            SocketChannel channel = SocketChannel.open();
            channel.connect(new InetSocketAddress("127.0.0.1",2323));
            ByteBuffer buf = ByteBuffer.allocate(2048);
            channel.configureBlocking(false);
            Scanner scanner = new Scanner(System.in);
            while(scanner.hasNext()){
                String msg = scanner.nextLine();
                buf.put((new Date()+":"+msg+"\r\n").getBytes());
                buf.flip();
                channel.write(buf);
                buf.clear();
            }

    }
}

参考地址:
java NIO 入门(良好排版格式)

猜你喜欢

转载自blog.csdn.net/qq_19107011/article/details/80802258