BIO、NIO、AIO之IO

一、BIO

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *   阻塞式服务端通信
 * @author zc
 *
 */
public class BIOServer {
	
	public static void main(String[] args) throws IOException {
		ServerSocket  serverSocket = new ServerSocket(9000);
		while(true) {
			
			System.out.println("服务器端等待连接...");
			//阻塞方法
			Socket socket = serverSocket.accept();
			System.out.println("有客户端连接....");
			handler(socket);
			
		}
		
	}

	private static void handler(Socket socket) throws IOException {
		//获得当前线程的id
		System.out.println(Thread.currentThread().getId());
		byte[] bytes = new byte[1024];
		System.out.println("准备read...");
		int read =socket.getInputStream().read(bytes);
		System.out.println("read完毕...");
		if(read!=-1) {
		  System.out.println("接收到客户端的数据"+ new String(bytes,0,read));	
		  System.out.println("thread id ="+Thread.currentThread().getId());
		}
		socket.getOutputStream().write("HelloClient".getBytes());
		socket.getOutputStream().flush();
	}

}

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 阻塞式客户端通信
 * @author zc
 *
 */
public class BIOClient {
      
	public static void main(String[] args) throws UnknownHostException, IOException {
		Socket socket  = new Socket("127.0.0.1",9000);
		//向服务端发送数据
		socket.getOutputStream().write("HelloServer".getBytes());
		socket.getOutputStream().flush();
		System.out.println("向服务器端发送数据结束");
		
		//接收服务器端传回来的的数据
		byte[] bytes =new byte[1024];
		socket.getInputStream().read(bytes);
		System.out.println("接收到服务器端的数据: "+ new String(bytes));
	    //关闭socket连接
		socket.close();
	}
}

二、NIO

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 {
	
	public static void main(String[] args) throws IOException {
		
		ServerSocketChannel ssc = ServerSocketChannel.open();
		
		ssc.configureBlocking(false);
		ssc.socket().bind(new InetSocketAddress(9000));
		
		//创建一个选择器 selector
		Selector selector = Selector.open();
		
		ssc.register(selector,SelectionKey.OP_ACCEPT);
		
		while(true) {
			
			System.out.println("等待事件的发生....");
			
			int select = selector.select();
			System.out.println("有事情发生了....");
			
			Iterator<SelectionKey> it= selector.selectedKeys().iterator();
			
			while(it.hasNext()) {
				SelectionKey key = it.next();
				it.remove();
				hanle(key);
				
			}
			
		}
	}

	private static void hanle(SelectionKey key) throws IOException {
		// TODO Auto-generated method stub
		if(key.isAcceptable()) {
			System.out.println("有客户端连接事件发生了....");
			ServerSocketChannel ssc= (ServerSocketChannel) key.channel();
			
			SocketChannel sc = ssc.accept();
			sc.configureBlocking(false);
			sc.register(key.selector(),SelectionKey.OP_READ);
		}else if(key.isReadable()) {
			
			System.out.println("有客户端可读事件发生了....");
			SocketChannel sc=(SocketChannel) key.channel();
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			int len =sc.read(buffer);
			if(len!=-1) {
				System.out.println("客户端发送的数据"+ new String(buffer.array(),0,len));
			}
			ByteBuffer bufferToWrite =ByteBuffer.wrap("HelloClient".getBytes());
			sc.write(bufferToWrite);
			key.interestOps(SelectionKey.OP_READ| SelectionKey.OP_WRITE);
		}else if(key.isWritable()) {
			SocketChannel sc=(SocketChannel) key.channel();
			System.out.println("客户端write事件发生了");
			key.interestOps(SelectionKey.OP_READ);
			
		}
		
	}

}

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;
	public static void main(String[] args) throws IOException {
		
		NIOClient client =new NIOClient();
		client.initClient("127.0.0.1",9000);
		client.connect();
		
	}

	private void connect() throws IOException {
		// TODO Auto-generated method stub
		 // 轮询访问selector
        while (true) {
            selector.select();
            // 获得selector中选中的项的迭代器
            Iterator<SelectionKey> it = this.selector.selectedKeys().iterator();
            while (it.hasNext()) {
                SelectionKey key = (SelectionKey) it.next();
                // 删除已选的key,以防重复处理
                it.remove();
                // 连接事件发生
                if (key.isConnectable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    // 如果正在连接,则完成连接
                    if (channel.isConnectionPending()) {
                        channel.finishConnect();
                    }
                    // 设置成非阻塞
                    channel.configureBlocking(false);
                    //在这里可以给服务端发送信息哦
                    ByteBuffer buffer = ByteBuffer.wrap("HelloServer".getBytes());
                    channel.write(buffer);
                    //在和服务端连接成功之后,为了可以接收到服务端的信息,需要给通道设置读的权限。
                    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(1024);
        int len = channel.read(buffer);
        if (len != -1) {
            System.out.println("客户端收到信息:" + new String(buffer.array(), 0, len));
        }
    }
	

	private void initClient(String ip, int port) throws IOException {
		// TODO Auto-generated method stub
		SocketChannel channel =SocketChannel.open();
		channel.configureBlocking(false);
		this.selector =Selector.open();
		channel.connect(new InetSocketAddress(ip,port));
		channel.register(selector, SelectionKey.OP_CONNECT);
		
	}
}

三、AIO

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 *  异步服务端接口
 * @author zc
 *
 */
public class AIOServer {

	  public static void main(String[] args) throws IOException, InterruptedException {
		
		 final AsynchronousServerSocketChannel  serverChannel= AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(9000));
		 
		 serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel,Object>() {

			@Override
			public void completed(AsynchronousSocketChannel socketChannel, Object arg1) {
				// TODO Auto-generated method stub
				try {
				
					System.out.println(socketChannel.getRemoteAddress());
					ByteBuffer buffer =ByteBuffer.allocate(1024);
					socketChannel.read(buffer,buffer,new CompletionHandler<Integer,ByteBuffer>(){

						@Override
						public void completed(Integer result, ByteBuffer attachment) {
							// TODO Auto-generated method stub
							buffer.flip();
							System.out.println(new String(buffer.array(),0,result));
							socketChannel.write(ByteBuffer.wrap("HelloClient".getBytes()));
						}

						@Override
						public void failed(Throwable exc, ByteBuffer attachment) {
							// TODO Auto-generated method stub
							exc.printStackTrace();
						}
						
					});
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void failed(Throwable arg0, Object arg1) {
				// TODO Auto-generated method stub
				arg0.printStackTrace();
			}
			 
		 });
		 
		 Thread.sleep(Integer.MAX_VALUE);
		 
	}
	
}

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;

/**
 * 异步调用客户端
 * @author zc
 *
 */
public class AIOClient {
	  public static void main(String...args) throws IOException, InterruptedException, ExecutionException {
		
		AsynchronousSocketChannel socketChannel =AsynchronousSocketChannel.open();
	    socketChannel.connect(new InetSocketAddress("127.0.0.1",9000)).get();
	    socketChannel.write(ByteBuffer.wrap("HelloServer".getBytes()));
	    ByteBuffer buffer =ByteBuffer.allocate(1024);
	    Integer len =socketChannel.read(buffer).get();
	    if(len != -1) {
	    	System.out.println("客户端接受消息"+ new String(buffer.array(),0,len));
	    }
	}
	

}

在这里插入图片描述
原文

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值