【七】Java NIO代碼例子(網絡和文件)

一、網絡IO TCP

服務端代碼

package com.sid.io.niov2;

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;

public class NIOServer {
    // 通道管理器
    private Selector selector;

    /**
     * 獲得一個ServerSocket通道,並對該通道做一些初始化的工作
     * @param port 綁定的端口號
     * @throws IOException
     */
    public void initServer(int port) throws IOException {
        // 獲得一個ServerSocketChannel通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 設置通道爲非阻塞
        serverSocketChannel.configureBlocking(false);
        // 將該通道對應的ServerSocket綁定到port端口
        serverSocketChannel.bind(new InetSocketAddress(port));
        // 獲得一個通道管理器
        this.selector = Selector.open();
        // 將通道管理器和該通道綁定,併爲該通道註冊SelectionKey.OP_ACCEPT事件,註冊該事件後,
        // 當該事件到達時,selector.select()會返回,如果該事件沒到達selector.select()會一直阻塞。
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    /**
     * 採用輪詢的方式監聽selector上是否有需要處理的事件,如果有,則進行處理
     * @throws IOException
     */
    public void listen() throws IOException {
        System.out.println("服務端啓動成功!");
        // 輪詢訪問selector
        while (true) {
            // 當註冊的事件到達時,方法返回;否則,該方法會一直阻塞
            selector.select();
            // 獲得selector中選中的項的迭代器,選中的項爲註冊的事件
            Iterator<SelectionKey> ite = this.selector.selectedKeys().iterator();
            while (ite.hasNext()) {
                SelectionKey key = (SelectionKey) ite.next();
                // 刪除已選的key,以防重複處理
                ite.remove();

                if (key.isAcceptable()) {// 客戶端請求連接事件
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    // 獲得和客戶端連接的通道
                    SocketChannel channel = server.accept();
                    // 設置成非阻塞
                    channel.configureBlocking(false);

                    // 在這裏可以給客戶端發送信息哦
                    channel.write(ByteBuffer.wrap(new String("服務端已經收到了你的連接")
                            .getBytes("utf-8")));
                    // 在和客戶端連接成功之後,爲了可以接收到客戶端的信息,需要給通道設置讀的權限。
                    channel.register(this.selector, SelectionKey.OP_READ);

                } else if (key.isReadable()) {// 獲得了可讀的事件
                    read(key);
                }

            }

        }
    }

    /**
     * 處理讀取客戶端發來的信息 的事件
     *
     * @param key
     * @throws IOException
     */
    public void read(SelectionKey key) throws IOException {
        // 服務器可讀取消息:得到事件發生的Socket通道
        SocketChannel channel = (SocketChannel) key.channel();
        // 創建讀取的緩衝區
        ByteBuffer buffer = ByteBuffer.allocate(512);
        channel.read(buffer);
        byte[] data = buffer.array();
        String msg = new String(data).trim();
        System.out.println("服務端收到信息:" + msg);
        ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes("utf-8"));
        channel.write(outBuffer);// 將消息回送給客戶端
    }

    /**
     * 啓動服務端測試
     *
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        NIOServer server = new NIOServer();
        server.initServer(8000);
        server.listen();
    }
}

客戶端

package com.sid.io.niov2;

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.SocketChannel;
import java.util.Iterator;

public class NIOClient {

    //通道管理器
    private Selector selector;

    /**
     * 獲得一個Socket通道,並對該通道做一些初始化的工作
     * @param ip 連接的服務器的ip
     * @param port  連接的服務器的端口號
     * @throws IOException
     */
    public void initClient(String ip,int port) throws IOException {
        // 獲得一個Socket通道
        SocketChannel channel = SocketChannel.open();
        // 設置通道爲非阻塞
        channel.configureBlocking(false);
        // 獲得一個通道管理器
        this.selector = Selector.open();

        // 客戶端連接服務器,其實方法執行並沒有實現連接,需要在listen()方法中調
        //用channel.finishConnect();才能完成連接
        channel.connect(new InetSocketAddress(ip,port));
        //將通道管理器和該通道綁定,併爲該通道註冊SelectionKey.OP_CONNECT事件。
        channel.register(selector, SelectionKey.OP_CONNECT);
    }

    /**
     * 採用輪詢的方式監聽selector上是否有需要處理的事件,如果有,則進行處理
     * @throws IOException
     */
    public void connect() throws IOException {
        // 輪詢訪問selector
        while (true) {
            // 選擇一組可以進行I/O操作的事件,放在selector中,客戶端的該方法不會阻塞(測試的時候發現阻塞了),
            //這裏和服務端的方法不一樣,查看api註釋可以知道,當至少一個通道被選中時,
            //selector的wakeup方法被調用,方法返回,而對於客戶端來說,通道一直是被選中的
            selector.select();
            // 獲得selector中選中的項的迭代器
            Iterator<SelectionKey> ite = this.selector.selectedKeys().iterator();
            while (ite.hasNext()) {
                SelectionKey key = (SelectionKey) ite.next();
                // 刪除已選的key,以防重複處理
                ite.remove();
                // 連接事件發生
                if (key.isConnectable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    // 如果正在連接,則完成連接
                    if(channel.isConnectionPending()){
                        channel.finishConnect();
                    }
                    // 設置成非阻塞
                    channel.configureBlocking(false);
                    //在這裏可以給服務端發送信息哦
                    channel.write(ByteBuffer.wrap(new String("向服務端發送了一條信息").getBytes("utf-8")));
                    //在和服務端連接成功之後,爲了可以接收到服務端的信息,需要給通道設置讀的權限。
                    channel.register(this.selector, SelectionKey.OP_READ);                                            // 獲得了可讀的事件
                } else if (key.isReadable()) {
                    read(key);
                }
            }
        }
    }
    /**
     * 處理讀取服務端發來的信息 的事件
     * @param key
     * @throws IOException
     */
    public void read(SelectionKey key) throws IOException{
        //和服務端的read方法一樣
        // 服務器可讀取消息:得到事件發生的Socket通道
        SocketChannel channel = (SocketChannel) key.channel();
        // 創建讀取的緩衝區
        ByteBuffer buffer = ByteBuffer.allocate(512);
        channel.read(buffer);
        byte[] data = buffer.array();
        String msg = new String(data).trim();
        System.out.println("客戶端收到信息:" + msg);
        //ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes("utf-8"));
        //channel.write(outBuffer);// 將消息回送給客戶端
    }


    /**
     * 啓動客戶端測試
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        NIOClient client = new NIOClient();
        client.initClient("localhost",8000);
        client.connect();
    }

}

二、網絡IO UDP

由於udp是一個無連接的協議,因此服務器端和客戶端的代碼基本相同。實際上服務器和客戶端之間並沒有太大區分。所以不存在ServerDatagramChannel這種玩意了,服務器端和客戶端都是創建一個DatagramChannel。然後bind一個端口,註冊Selector之後就可以打開監聽了。

服務端

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;
 
public class NIOUdpServer implements Runnable {
    private int port;
 
    public NIOUdpServer(int port) {
        this.port = port;
        new Thread(this).start();
    }
 
    public void run() {
        try {
            // 建立
            DatagramChannel dc = DatagramChannel.open();
            dc.configureBlocking(false);
            SocketAddress address = new InetSocketAddress(port);
            // 本地綁定端口
            DatagramSocket ds = dc.socket();
            ds.setReceiveBufferSize(20480);
            ds.bind(address);
            // 註冊
            Selector select = Selector.open();
            dc.register(select, SelectionKey.OP_READ);
            System.out.println("Listening on port " + port);
            ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
            int number = 0; // 只爲記錄接受的字節數
            while (true) {
                int num = select.select();
                // 如果選擇器數目爲0,則結束循環
                if (num == 0) {
                    continue;
                }
                // 得到選擇鍵列表
                Set Keys = select.selectedKeys();
                Iterator it = Keys.iterator();
                while (it.hasNext()) {
                    SelectionKey k = (SelectionKey) it.next();
                    if ((k.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
 
                        DatagramChannel cc = (DatagramChannel) k.channel();
                        // 非阻塞
                        cc.configureBlocking(false);
 
                        // 接收數據並讀到buffer中
                        buffer.clear();
                        SocketAddress client = cc.receive(buffer);
 
                        buffer.flip();
                        if (buffer.remaining() <= 0) {
                            System.out.println("bb is null");
                        }
                        // 記錄接收到的字節總數
                        number += buffer.remaining();
                        byte b[] = new byte[buffer.remaining()];
                        for (int i = 0; i < buffer.remaining(); i++) {
                            b[i] = buffer.get(i);
                        }
                        String in = new String(b, "gb2312");
                        System.out.println("number::::" + number);
                        // 執行操作,並回發送
                    }
                }
                Keys.clear();
            }
 
        } catch (IOException ie) {
            System.err.println(ie);
        }
    }
 
    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        int port = 1111;
        new NIOUdpServer(port);
    }
     
}

客戶端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
 
public class NIOUdpClient extends Thread {
     
    private String host;
    private int port;
    int j = 0;
    int number;
 
    public NIOUdpClient(String host, int port, int numThreads) {
        this.host = host;
        this.port = port;
 
        for (int i = 0; i < numThreads; ++i) {
            new Thread(this).start();
        }
    }
 
    public void run() {
        // 構造一個數據報Socket
        DatagramChannel dc = null;
        try {
            dc = DatagramChannel.open();
        } catch (IOException ex4) {
        }
        SocketAddress address = new InetSocketAddress(host, port);
        try {
            dc.connect(address);
        } catch (IOException ex) {
        }
        // 發送請求
        ByteBuffer bb = ByteBuffer.allocate(130);
 
        byte[] b = new byte[130];
        String s = "sdfas";
 
        s = "sss";
 
        b = s.getBytes();
        bb.clear();
        bb.put(b);
        bb.flip();
        // 測試
        if (bb.remaining() <= 0) {
            System.out.println("bb is null");
        }
        try {
            int num = dc.send(bb, address);
            number = number + num;
 
            System.out.println("number:::" + number);
 
            bb.clear();
            dc.receive(bb);
            bb.flip();
            byte[] by = new byte[bb.remaining()];
            for (int i = 0; i < bb.remaining(); i++) {
                by[i] = bb.get(i);
            }
            String ss = new String(by, "gb2312");
            System.out.println(ss);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        String host = "127.0.0.1";
        int port = 1111;
        int numThreads = 3;
        new NIOUdpClient(host, port, numThreads);
    }
 
}

 

三、本地文件IO

package com.sid.io.niov2;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class NIOFileCopy {
    public static void fileCopyByNIO(String resource,String destination) throws Exception{

        FileInputStream fileInputStream = new FileInputStream(resource);
        FileOutputStream fileOutputStream = new FileOutputStream(destination);

        FileChannel fileReadChannel = fileInputStream.getChannel();
        FileChannel fileWriteChannel = 	fileOutputStream.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.clear();
        int len = 0;
        while((len=fileReadChannel.read(buffer))!=-1){
            buffer.flip();
            fileWriteChannel.write(buffer);
            buffer.clear();
        }

        fileReadChannel.close();
        fileWriteChannel.close();

    }


    public static void operFileMapped(String file) throws Exception{

        RandomAccessFile raf = new RandomAccessFile(file, "rw");

        FileChannel fc = raf.getChannel();

        MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, raf.length());

		/*
		while(mbb.hasRemaining()){
			System.out.println((char)mbb.get());
		}
		*/
        byte index0 =  mbb.get(0);
        System.out.println(index0);

        mbb.put(0,(byte)-119);

        raf.close();

    }


    public static void main(String[] args) {

		/*
		try {
			NIOFileCopy.fileCopyByNIO("D:\\projects\\testWeb\\src\\zmx\\nio\\test\\test.txt", "D:\\projects\\testWeb\\src\\zmx\\nio\\test\\copy.txt");
		} catch (Exception e) {
			e.printStackTrace();
		}
		*/

        try {
            NIOFileCopy.operFileMapped("D:\\projects\\testWeb\\src\\zmx\\nio\\test\\yumi.png");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章