天天看點

Java IO模型

BIO 阻塞IO

一個連接配接,一個線程,且讀寫阻塞。

服務端

package com.xiaowuqin.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {
    public static void main(String[] args) throws IOException {
        //線程池機制

        //思路
        //先建立一個線程池
        //如果有個新連接配接就單獨建立一個線程

        ExecutorService executorService = Executors.newCachedThreadPool();
        //建立一個serversocket
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("伺服器啟動了~");
        while(true){
            //監聽.等待用戶端連接配接
            final Socket socket = serverSocket.accept();
            System.out.println("有一個新用戶端連接配接了");

          //單獨建立一個線程
            executorService.execute(new Runnable() {
                public void run() {
                    //可以和用戶端通信
                    handler(socket);
                }
            });
        }
    }
    static void handler(Socket socket) {

        try{
            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            //循環讀取資料
            while(true){
                int read = inputStream.read(bytes);
                if(read != -1) System.out.println(new String(bytes,0,read));
                else break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                socket.close();
                System.out.println("連接配接已經關閉~");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

           

打開cmd視窗,輸入

即可連接配接成功

Java IO模型

在cmd telnet視窗中Ctrl+] 後就可以發送資料

send   你要發送的資料内容
           
Java IO模型

NIP 同步非阻塞IO

服務端

package com.xiaowuqin.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Set;

public class NIOServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        Selector selector = Selector.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //設定為非阻塞
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);//連接配接事件
        //循環等待用戶端連接配接
        while(true){
            if(selector.select() == 0){
                System.out.println("還沒有事件發生~");
                continue;
            }else{
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                for(SelectionKey sti:selectionKeys){
                    //根據不同的事件,作不同的處理
                    if(sti.isAcceptable()){
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));

                    }
                    if(sti.isReadable()){
                        SocketChannel channel = (SocketChannel)sti.channel();
                        ByteBuffer buffer = (ByteBuffer)sti.attachment();
                        channel.read(buffer);
                        System.out.println("用戶端發送了:"+new String(buffer.array()));

                    }
                    selectionKeys.remove(sti);
                }
            }
        }
    }
}

           

用戶端

package com.xiaowuqin.nio;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NIOClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        //設定非阻塞
        socketChannel.configureBlocking(false);

        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
        if(!socketChannel.connect(inetSocketAddress)){
            while(!socketChannel.finishConnect()){
                System.out.println("連接配接需要時間,目前沒有成功,可以作其它事情~");
            }
        }
        //連接配接成功,發送消息
        String a = "123";
        ByteBuffer byteBuffer = ByteBuffer.wrap(a.getBytes());
        socketChannel.write(byteBuffer);
        System.in.read();
    }
}