网络编程基础BIO、NIO、AIO

41 篇文章 0 订阅
26 篇文章 0 订阅

1,网络编程基础
      1),网络编程(Socket)概念 :

              首先注意, Socket不是Java中独有的概念,而是一个语言无关标准。 任何可以实现网络编程的编程语言都有Socket 。

       2),什么是 Socket :
                        网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个 socket。

       3),Socket 连接步骤:

                   连接过程可以分为三 个步骤:服务器监听,客户端请求,连接确认。(如果包含数据交互+断开连接,那么一共是 五个步骤)

               (1)服务器监听:是服务器端套接字并不定位具体的客户端套接字,而是处于等待连 接的状态,实时监控网络状态。                               (2)客户端请求:是指由客户端的套接字提出连接请求,要连接的目标是服务器端的 套接字。为此,客户端的套接字必须首先描述它要连接的服务器的套接字,指出服务器端套 接字的地址和端口号,然后就向服务器端套接字提出连接请求。

               (3)连接确认:是指当服务器端套接字监听到或者说接收到客户端套接字的连接请求, 它就响应客户端套接字的请求,建立一个新的线程,把服务器端套接字的描述发给客户端, 一旦客户端确认了此描述,连接就建立好了。而服务器端套接字继续处于监听状态,继续接 收其他客户端套接字的连接请求。 

                   客户端与服务端建立连接过程:三次握手; 客户端与服务端断开连接过程:四次挥手

                    

      4),Java 中的 Socket :

    在 java.net 包是网络编程的基础类库。其中 ServerSocket 和 Socket 是网络编程的基础类 型。ServerSocket 是服务端应用类型。Socket 是建立连接的类型。当连接建立成功后,服务 器和客户端都会有一个 Socket 对象示例,可以通过这个 Socket 对象示例,完成会话的所有 操作。

  对于一个完整的网络连接来说,Socket 是平等的,没有服务器客户端分级情况。

      5),什么是同步和异步:
              同步和异步是针对应用程序和内核的交互而言的,同步指的是用户进程触发 IO 操作并 等待或者轮询的去查看 IO 操作是否就绪,而异步是指用户进程触发 IO 操作以后便开始做自 己的事情,而当 IO 操作已经完成的时候会得到 IO 完成的通知。 

      6), 什么是阻塞和非阻塞:

   阻塞和非阻塞是针对于进程在访问数据的时候,根据 IO 操作的就绪状态来采取的不同 方式,说白了是一种读取或者写入操作方法的实现方式,阻塞方式下读取或者写入函数将一 直等待,而非阻塞方式下,读取或者写入方法会立即返回一个状态值。

 

2,BIO 编程 : 同步阻塞的编程方式。 

  1),BIO 编程方式通常是在 JDK1.4 版本之前常用的编程方式。编程实现过程为:首先在服务 端启动一个 ServerSocket 来监听网络请求,客户端启动 Socket 发起网络请求,默认情况下 ServerSocket 回建立一个线程来处理此请求,如果服务端没有线程可用,客户端则会阻塞等 待或遭到拒绝。 且建立好的连接,在通讯过程中,是同步的。在并发处理效率上比较低。大致结构如下:


               Server.java              

public class Server {
	public static void main(String[] args) {
		int port = genPort(args);
		ServerSocket server = null;
		try{
			server = new ServerSocket(port);
			System.out.println("server started!");
			while(true){
				Socket socket = server.accept();		
				new Thread(new Handler(socket)).start();
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(server != null){
				try {
					server.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			server = null;
		}
	}
	
	static class Handler implements Runnable{
		Socket socket = null;
		public Handler(Socket socket){
			this.socket = socket;
		}
		@Override
		public void run() {
			BufferedReader reader = null;
			PrintWriter writer = null;
			try{	
				reader = new BufferedReader(
						new InputStreamReader(socket.getInputStream(), "UTF-8"));
				writer = new PrintWriter(
						new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
				String readMessage = null;
				while(true){
					System.out.println("server reading... ");
					if((readMessage = reader.readLine()) == null){
						break;
					}
					System.out.println(readMessage);
					writer.println("server recive : " + readMessage);
					writer.flush();
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				if(socket != null){
					try {
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				socket = null;
				if(reader != null){
					try {
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				reader = null;
				if(writer != null){
					writer.close();
				}
				writer = null;
			}
		}
		
	}
	private static int genPort(String[] args){
		if(args.length > 0){
			try{
				return Integer.parseInt(args[0]);
			}catch(NumberFormatException e){
				return 9999;
			}
		}else{
			return 9999;
		}
	}
	
}

         Client.java         

public class Client {
	public static void main(String[] args) {
		String host = null;
		int port = 0;
		if(args.length > 2){
			host = args[0];
			port = Integer.parseInt(args[1]);
		}else{
			host = "127.0.0.1";
			port = 9999;
		}
		
		Socket socket = null;
		BufferedReader reader = null;
		PrintWriter writer = null;
		Scanner s = new Scanner(System.in);
		try{
			socket = new Socket(host, port);
			String message = null;
			
			reader = new BufferedReader(
					new InputStreamReader(socket.getInputStream(), "UTF-8"));
			writer = new PrintWriter(
					socket.getOutputStream(), true);
			while(true){
				message = s.nextLine();
				if(message.equals("exit")){
					break;
				}
				writer.println(message);
				writer.flush();
				System.out.println(reader.readLine());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(socket != null){
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			socket = null;
			if(reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			reader = null;
			if(writer != null){
				writer.close();
			}
			writer = null;
		}
	}
}

                2),同步并阻塞,服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就 需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销,当然可 以通过线程池机制改善。 BIO 方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高,并发局限于应用中,JDK1.4 以前的唯一选择,但程序直观简单易理解。 使用线程池机制改善后的 BIO 模型图如下: 

                         
 

3,NIO 编程 : 同步非阻塞的编程方式     --- JDK1.4 以上版本开始支持

    主要想解决的是 BIO 的大并发问题,NIO 基 于 Reactor,当 socket 有流可读或可写入 socket 时,操作系统会相应的通知引用程序进行处 理,应用再将流读取到缓冲区或写入操作系统。也就是说,这个时候,已经不是一个连接就 要对应一个处理线程了,而是有效的请求,对应一个线程,当连接没有数据时,是没有工作 线程来处理的。             

               当一个连接创建后,这个连接会被注册到 多路复用器 上面,所以所有的连接只需要一个线程就可以搞定,当这个线程中的多路复用器 进行轮询的时候,发现连接上有请求的话,才开启一个线程进行处理,也就是一个请求一个 线程模式。

    在 NIO 的处理方式中,当一个请求来的话,开启线程进行处理,可能会等待后端应用的资源(JDBC 连接等),其实这个线程就被阻塞了,当并发上来的话,还是会有 BIO 一样的问题。

   大致模型图:

       

 

同步非阻塞,服务器实现模式为一个请求一个通道,即客户端发送的连接请求都会注册 到多路复用器上,多路复用器轮询到连接有 I/O 请求时才启动一个线程进行处理。 NIO 方式适用于连接数目多且连接比较短(轻操作)的架构,比如聊天服务器,并发局 限于应用中,编程复杂,JDK1.4 开始支持。 

Server.java

public class NIOServer implements Runnable {

	// 多路复用器, 选择器。 用于注册通道的。
	private Selector selector;
	// 定义了两个缓存。分别用于读和写。 初始化空间大小单位为字节。
	private ByteBuffer readBuffer = ByteBuffer.allocate(1024);
	private ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
	
	public static void main(String[] args) {
		new Thread(new NIOServer(9999)).start();
	}
	
	public NIOServer(int port) {
		init(port);
	}
	
	private void init(int port){
		try {
			System.out.println("server starting at port " + port + " ...");
			// 开启多路复用器
			this.selector = Selector.open();
			// 开启服务通道
			ServerSocketChannel serverChannel = ServerSocketChannel.open();
			// 非阻塞, 如果传递参数true,为阻塞模式。
			serverChannel.configureBlocking(false);
			// 绑定端口
			serverChannel.bind(new InetSocketAddress(port));
			// 注册,并标记当前服务通道状态
			/*
			 * register(Selector, int)
			 * int - 状态编码
			 *  OP_ACCEPT : 连接成功的标记位。
			 *  OP_READ : 可以读取数据的标记
			 *  OP_WRITE : 可以写入数据的标记
			 *  OP_CONNECT : 连接建立后的标记
			 */
			serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
			System.out.println("server started.");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run(){
		while(true){
			try {
				// 阻塞方法,当至少一个通道被选中,此方法返回。
				// 通道是否选择,由注册到多路复用器中的通道标记决定。
				this.selector.select();
				// 返回以选中的通道标记集合, 集合中保存的是通道的标记。相当于是通道的ID。
				Iterator<SelectionKey> keys = this.selector.selectedKeys().iterator();
				while(keys.hasNext()){
					SelectionKey key = keys.next();
					// 将本次要处理的通道从集合中删除,下次循环根据新的通道列表再次执行必要的业务逻辑
					keys.remove();
					// 通道是否有效
					if(key.isValid()){
						// 阻塞状态
						try{
							if(key.isAcceptable()){
								accept(key);
							}
						}catch(CancelledKeyException cke){
							// 断开连接。 出现异常。
							key.cancel();
						}
						// 可读状态
						try{
							if(key.isReadable()){
								read(key);
							}
						}catch(CancelledKeyException cke){
							key.cancel();
						}
						// 可写状态
						try{
							if(key.isWritable()){
								write(key);
							}
						}catch(CancelledKeyException cke){
							key.cancel();
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}
	
	private void write(SelectionKey key){
		this.writeBuffer.clear();
		SocketChannel channel = (SocketChannel)key.channel();
		Scanner reader = new Scanner(System.in);
		try {
			System.out.print("put message for send to client > ");
			String line = reader.nextLine();
			// 将控制台输入的字符串写入Buffer中。 写入的数据是一个字节数组。
			writeBuffer.put(line.getBytes("UTF-8"));
			writeBuffer.flip();
			channel.write(writeBuffer);
			
			channel.register(this.selector, SelectionKey.OP_READ);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void read(SelectionKey key){
		try {
			// 清空读缓存。
			this.readBuffer.clear();
			// 获取通道
			SocketChannel channel = (SocketChannel)key.channel();
			// 将通道中的数据读取到缓存中。通道中的数据,就是客户端发送给服务器的数据。
			int readLength = channel.read(readBuffer);
			// 检查客户端是否写入数据。
			if(readLength == -1){
				// 关闭通道
				key.channel().close();
				// 关闭连接
				key.cancel();
				return;
			}
			/*
			 * flip, NIO中最复杂的操作就是Buffer的控制。
			 * Buffer中有一个游标。游标信息在操作后不会归零,如果直接访问Buffer的话,数据有不一致的可能。
			 * flip是重置游标的方法。NIO编程中,flip方法是常用方法。
			 */
			this.readBuffer.flip();
			// 字节数组,保存具体数据的。 Buffer.remaining() -> 是获取Buffer中有效数据长度的方法。
			byte[] datas = new byte[readBuffer.remaining()];
			// 是将Buffer中的有效数据保存到字节数组中。
			readBuffer.get(datas);
			System.out.println("from " + channel.getRemoteAddress() + " client : " + new String(datas, "UTF-8"));
			
			// 注册通道, 标记为写操作。
			channel.register(this.selector, SelectionKey.OP_WRITE);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				key.channel().close();
				key.cancel();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	private void accept(SelectionKey key){
		try {
			// 此通道为init方法中注册到Selector上的ServerSocketChannel
			ServerSocketChannel serverChannel = (ServerSocketChannel)key.channel();
			// 阻塞方法,当客户端发起请求后返回。 此通道和客户端一一对应。
			SocketChannel channel = serverChannel.accept();
			channel.configureBlocking(false);
			// 设置对应客户端的通道标记状态,此通道为读取数据使用的。
			channel.register(this.selector, SelectionKey.OP_READ);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}

          Client.java            

public class NIOClient {

	public static void main(String[] args) {
		// 远程地址创建
		InetSocketAddress remote = new InetSocketAddress("localhost", 9999);
		SocketChannel channel = null;
		
		// 定义缓存。
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		
		try {
			// 开启通道
			channel = SocketChannel.open();
			// 连接远程服务器。
			channel.connect(remote);
			Scanner reader = new Scanner(System.in);
			while(true){
				System.out.print("put message for send to server > ");
				String line = reader.nextLine();
				if(line.equals("exit")){
					break;
				}
				// 将控制台输入的数据写入到缓存。
				buffer.put(line.getBytes("UTF-8"));
				// 重置缓存游标
				buffer.flip();
				// 将数据发送给服务器
				channel.write(buffer);
				// 清空缓存数据。
				buffer.clear();

				// 读取服务器返回的数据
				int readLength = channel.read(buffer);
				if(readLength == -1){
					break;
				}
				// 重置缓存游标
				buffer.flip();
				byte[] datas = new byte[buffer.remaining()];
				// 读取数据到字节数组。
				buffer.get(datas);
				System.out.println("from server : " + new String(datas, "UTF-8"));
				// 清空缓存。
				buffer.clear();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(null != channel){
				try {
					channel.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}

4,AIO 编程 :异步非阻塞的编程方式    ----- jdk1.7以上版本开始支持

 与 NIO 不同,当进行读写操作时,只须直接调用 API 的 read 或 write 方法即可。这两种 方法均为异步的,对于读操作而言,当有流可读取时,操作系统会将可读的流传入 read 方 法的缓冲区,并通知应用程序;对于写操作而言,当操作系统将 write 方法传递的流写入完 毕时,操作系统主动通知应用程序。

异步非阻塞,服务器实现模式为一个有效请求一个线程,客户端的 I/O 请求都是由 OS 先完成了再通知服务器应用去启动线程进行处理。 AIO 方式使用于连接数目多且连接比较长(重操作)的架构,比如相册服务器,充分调 用 OS 参与并发操作,编程比较复杂。

大致流程图:

           

          AIOServer.java                   

public class AIOServer {

	// 线程池, 提高服务端效率。
	private ExecutorService service;
	// 线程组
	// private AsynchronousChannelGroup group;
	// 服务端通道, 针对服务器端定义的通道。
	private AsynchronousServerSocketChannel serverChannel;
	
	public AIOServer(int port){
		init(9999);
	}
	
	private void init(int port){
		try {
			System.out.println("server starting at port : " + port + " ...");
			// 定长线程池
			service = Executors.newFixedThreadPool(4);
			/* 使用线程组
			group = AsynchronousChannelGroup.withThreadPool(service);
			serverChannel = AsynchronousServerSocketChannel.open(group);
			*/
			// 开启服务端通道, 通过静态方法创建的。
			serverChannel = AsynchronousServerSocketChannel.open();
			// 绑定监听端口, 服务器启动成功,但是未监听请求。
			serverChannel.bind(new InetSocketAddress(port));
			System.out.println("server started.");
			// 开始监听 
			// accept(T attachment, CompletionHandler<AsynchronousSocketChannel, ? super T>)
			// AIO开发中,监听是一个类似递归的监听操作。每次监听到客户端请求后,都需要处理逻辑开启下一次的监听。
			// 下一次的监听,需要服务器的资源继续支持。
			serverChannel.accept(this, new AIOServerHandler());
			try {
				TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		new AIOServer(9999);
	}

	public ExecutorService getService() {
		return service;
	}

	public void setService(ExecutorService service) {
		this.service = service;
	}

	public AsynchronousServerSocketChannel getServerChannel() {
		return serverChannel;
	}

	public void setServerChannel(AsynchronousServerSocketChannel serverChannel) {
		this.serverChannel = serverChannel;
	}
	
}

          AIOServerHandler.java                   

public class AIOServerHandler implements CompletionHandler<AsynchronousSocketChannel, AIOServer> {

	/**
	 * 业务处理逻辑, 当请求到来后,监听成功,应该做什么。
	 * 一定要实现的逻辑: 为下一次客户端请求开启监听。accept方法调用。
	 * result参数 : 就是和客户端直接建立关联的通道。
	 *  无论BIO、NIO、AIO中,一旦连接建立,两端是平等的。
	 *  result中有通道中的所有相关数据。如:OS操作系统准备好的读取数据缓存,或等待返回数据的缓存。
	 */
	@Override
	public void completed(AsynchronousSocketChannel result, AIOServer attachment) {
		// 处理下一次的客户端请求。类似递归逻辑
		attachment.getServerChannel().accept(attachment, this);
		doRead(result);
	}

	/**
	 * 异常处理逻辑, 当服务端代码出现异常的时候,做什么事情。
	 */
	@Override
	public void failed(Throwable exc, AIOServer attachment) {
		exc.printStackTrace();
	}
	
	/**
	 * 真实项目中,服务器返回的结果应该是根据客户端的请求数据计算得到的。不是等待控制台输入的。
	 * @param result
	 */
	private void doWrite(AsynchronousSocketChannel result){
		try {
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			System.out.print("enter message send to client > ");
			Scanner s = new Scanner(System.in);
			String line = s.nextLine();
			buffer.put(line.getBytes("UTF-8"));
			// 重点:必须复位,必须复位,必须复位
			buffer.flip();
			// write方法是一个异步操作。具体实现由OS实现。 可以增加get方法,实现阻塞,等待OS的写操作结束。
			result.write(buffer);
			// result.write(buffer).get(); // 调用get代表服务端线程阻塞,等待写操作完成
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}/* catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}*/
	}
	
	private void doRead(final AsynchronousSocketChannel channel){
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		/*
		 * 异步读操作, read(Buffer destination, A attachment, 
		 *                    CompletionHandler<Integer, ? super A> handler)
		 * destination - 目的地, 是处理客户端传递数据的中转缓存。 可以不使用。
		 * attachment - 处理客户端传递数据的对象。 通常使用Buffer处理。
		 * handler - 处理逻辑
		 */
		channel.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {

			/**
			 * 业务逻辑,读取客户端传输数据
			 * attachment - 在completed方法执行的时候,OS已经将客户端请求的数据写入到Buffer中了。
			 *  但是未复位(flip)。 使用前一定要复位。
			 */
			@Override
			public void completed(Integer result, ByteBuffer attachment) {
				try {
					System.out.println(attachment.capacity());
					// 复位
					attachment.flip();
					System.out.println("from client : " + new String(attachment.array(), "UTF-8"));
					doWrite(channel);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void failed(Throwable exc, ByteBuffer attachment) {
				exc.printStackTrace();
			}
		});
	}

}

              AIOClient.java                    

public class AIOClient {
	
	private AsynchronousSocketChannel channel;
	
	public AIOClient(String host, int port){
		init(host, port);
	}
	
	private void init(String host, int port){
		try {
			// 开启通道
			channel = AsynchronousSocketChannel.open();
			// 发起请求,建立连接。
			channel.connect(new InetSocketAddress(host, port));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void write(String line){
		try {
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			buffer.put(line.getBytes("UTF-8"));
			buffer.flip();
			channel.write(buffer);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	public void read(){
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		try {
			// read方法是异步方法,OS实现的。get方法是一个阻塞方法,会等待OS处理结束后再返回。
			channel.read(buffer).get();
			// channel.read(dst, attachment, handler);
			buffer.flip();
			System.out.println("from server : " + new String(buffer.array(), "UTF-8"));
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	public void doDestory(){
		if(null != channel){
			try {
				channel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		AIOClient client = new AIOClient("localhost", 9999);
		try{
			System.out.print("enter message send to server > ");
			Scanner s = new Scanner(System.in);
			String line = s.nextLine();
			client.write(line);
			client.read();
		}finally{
			client.doDestory();
		}
	}

}

 

 

 

 

 

 

 

    
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java的艺术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值