Java NIO示例

給出Java NIO的示例。包含客戶端和服務端。java

示例

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

/** * NIOServer */
public class NIOServer {
    private Selector selector;
    ServerSocketChannel serverSocketChannel;

    public void initServer(int port) throws IOException {
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket().bind(new InetSocketAddress("localhost", port));
        this.selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    public void listen() throws IOException {
        System.out.println("server started succeed!");
        while (true) {
            selector.select();
            Iterator<SelectionKey> ite = selector.selectedKeys().iterator();
            while (ite.hasNext()) {
                SelectionKey key = ite.next();
                if(key.isAcceptable()) {
                    SocketChannel channel = serverSocketChannel.accept();
                    channel.configureBlocking(false);
                    channel.register(selector, SelectionKey.OP_READ);
                } else if(key.isReadable()) {
                    recvAndReply(key);
                }
                ite.remove();
            }
        }
    }

    public void recvAndReply(SelectionKey key) throws IOException {
        SocketChannel channel = (SocketChannel)key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(256);
        int i = channel.read(buffer);
        if (i != -1) { //用於判斷客戶端是否斷開了鏈接
            String msg = new String(buffer.array()).trim();
            System.out.println("server received message: " + msg);
            System.out.println("server reply: " + msg);
            channel.write(ByteBuffer.wrap(msg.getBytes()));
        } else {
            channel.close(); //若是客戶端斷開鏈接就關閉該鏈接
        }

    }

    public static void main(String[] args) throws IOException {
        NIOServer server = new NIOServer();
        server.initServer(7788);
        server.listen();
    }
}複製代碼
  • NIOClient.java
import java.io.IOError;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SocketChannel;
import java.nio.ByteBuffer;

/** * NIOClient */
public class NIOClient {
    SocketChannel channel;

    public void initClient(String host, int port) throws IOException {
        InetSocketAddress servAddr = new InetSocketAddress(host, port);
        this.channel = SocketChannel.open(servAddr);
    }

    public void sendAndRecv(String words) throws IOException {
        byte[] msg = new String(words).getBytes();
        ByteBuffer buffer = ByteBuffer.wrap(msg);
        System.out.println("sending: " + words);
        channel.write(buffer);
        buffer.clear();
        channel.read(buffer);
        System.out.println("received: " + new String(buffer.array()).trim());

        buffer.clear();
        System.out.println("sending: " + "again");
        buffer = ByteBuffer.wrap(new String("again").getBytes());
        channel.write(buffer);
        buffer.clear();
        channel.read(buffer);
        System.out.println("received: " + new String(buffer.array()).trim());

        channel.close();
    }

    public static void main(String[] args) throws IOException{
        NIOClient client = new NIOClient();
        client.initClient("localhost", 7788);
        client.sendAndRecv("this is client");
    }
}複製代碼

運行

程序運行順序以下:bash

  1. 運行NIOServer
  2. 運行NIOClient

輸出

  • NIOServer
server started succeed!
server received message: this is client
server reply: this is client
server received message: again
server reply: again複製代碼
  • NIOClient
sending: this is client
received: this is client
sending: again
received: again

Process finished with exit code 0複製代碼

可進入個人博客查看原文socket

歡迎關注公衆號: FullStackPlan 獲取更多幹貨
歡迎關注公衆號: FullStackPlan 獲取更多幹貨
相關文章
相關標籤/搜索