NIO服務器和客戶端通訊簡單例子

NIO服務器和客戶端通訊簡單例子

廢話不多說直接上代碼。
首先是服務端代碼:

package nio;

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;

public class NioServer {

    public Selector selector;

    //初始化服務器
    public void initServer(int port) throws Exception{
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //非阻塞
        serverSocketChannel.configureBlocking(false);
        //綁定端口
        serverSocketChannel.bind(new InetSocketAddress(port));
        //獲取一個通道管理器
        selector = Selector.open();
        //1.綁定通道管理器;
        //2.當事件到達時,selector.seletor()會返回否則會一直阻塞,此時註冊的是OP_ACCEPT事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    //監聽事件並處理
    public void listen() throws Exception{
        while(true){
            //當事件到達時,selector.seletor()會返回否則會一直阻塞
            selector.select();
            System.out.println("接收到了");
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while(iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                handle(selectionKey);
            }
        }
    }

    //處理
    public void handle(SelectionKey selectionKey) throws Exception{
        if(selectionKey.isAcceptable()){
            handleaccept(selectionKey);
        }else if(selectionKey.isReadable()){
            handleread(selectionKey);
        }
    }

    //如果接收到客戶端請求則將該channel改成監聽on_read狀態
    public void handleaccept(SelectionKey selectionKey) throws Exception{
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
        SocketChannel socketChannel = serverSocketChannel.accept();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
    }

    public void handleread(SelectionKey selectionKey) throws Exception{
        //取消讀事件的監控
        selectionKey.cancel();
        SocketChannel readChannel = (SocketChannel) selectionKey.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.clear();
        readChannel.read(buffer);
        System.out.println("服務器端接收到的數據:"+ new String(buffer.array()).trim());
    }

    public static void main(String[] args) throws Exception {
        NioServer server = new NioServer();
        server.initServer(8000);
        server.listen();
    }
}

客戶端代碼:

package nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NioClient {
    public static void main(String[] args) throws Exception {
        SocketChannel socketChannel = SocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(8000);
        socketChannel.connect(inetSocketAddress);
        String msg="我是客戶端"+Thread.currentThread().getId();
        ByteBuffer buffer=ByteBuffer.allocate(1024);
        buffer.put(msg.getBytes());
        buffer.flip();
        socketChannel.write(buffer);
        socketChannel.shutdownOutput();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章