Java NIO2 -- AIO Callable -- Future

5人阅读 评论(0) 收藏 举报
分类:
package com.xiuye.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class NIO2_AIO_Server1 {

	private ExecutorService taskExecutor;
	private AsynchronousServerSocketChannel serverChannel;
	class Worker implements Callable<String>{

		private CharBuffer charBuffer;
		private CharsetDecoder decoder = Charset.defaultCharset().newDecoder();
		private AsynchronousSocketChannel channel;
		public Worker(AsynchronousSocketChannel channel) {
			this.channel = channel;
		}

		@Override
		public String call() throws Exception {

			final ByteBuffer buffer = ByteBuffer.allocate(1024);
			while(channel.read(buffer).get() != -1){
				buffer.flip();
				charBuffer = decoder.decode(buffer);
				String request = charBuffer.toString().trim();
				System.out.println("Client Request MSG: "+request);
				ByteBuffer outBuffer = ByteBuffer.wrap("Request Received!".getBytes());
				channel.write(outBuffer).get();
				if(buffer.hasRemaining()){
					buffer.compact();
				}
				else{
					buffer.clear();
				}
			}

			channel.close();
			return "OK";
		}

	}

	public void init() throws IOException{
		taskExecutor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
		serverChannel = AsynchronousServerSocketChannel.open();
		if(serverChannel.isOpen()){
			serverChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4*1024);
			serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
			serverChannel.bind(new InetSocketAddress(8080));
		}
		else{
			throw new RuntimeException("Channel not opened!");
		}
	}

	public void start(){
		System.out.println("Wait for client ...");
		while(true){//虽然是异步还是有循环啊
			Future<AsynchronousSocketChannel> future = serverChannel.accept();

			AsynchronousSocketChannel channel;
			try {
				channel = future.get();
				taskExecutor.submit(new Worker(channel));
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
				System.err.println("Server closed!");
				while(!taskExecutor.isTerminated()){}
				break;
			}



		}
	}

	public static void main(String[] args) throws IOException {

		NIO2_AIO_Server1 server = new NIO2_AIO_Server1();
		server.init();
		server.start();

	}

}


package com.xiuye.nio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.concurrent.ExecutionException;

public class NIO2_AIO_Client1 {

	private AsynchronousSocketChannel channel;
	private CharBuffer charBuffer;
	private CharsetDecoder decoder = Charset.defaultCharset().newDecoder();
	private BufferedReader clientInput = new BufferedReader(new InputStreamReader(System.in));

	public void init() throws IOException, InterruptedException, ExecutionException{
		channel = AsynchronousSocketChannel.open();
		if(channel.isOpen()){
			channel.setOption(StandardSocketOptions.SO_RCVBUF, 128*1024);
			channel.setOption(StandardSocketOptions.SO_SNDBUF, 128*1024);
			channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
			Void connect = channel.connect(new InetSocketAddress("127.0.0.1",8080)).get();
			if(connect != null){
				throw new RuntimeException("connect failed!");
			}

		}
		else{
			throw new RuntimeException("Channel not opened!");
		}
	}

	public void start() throws IOException, InterruptedException, ExecutionException{
		System.out.println("Input Client Resqust MSG:");
		String request = clientInput.readLine();
		channel.write(ByteBuffer.wrap(request.getBytes()));
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		while(channel.read(buffer).get() != -1){
			buffer.flip();
			charBuffer = decoder.decode(buffer);
			String response = charBuffer.toString().trim();
			System.out.println("Server replied MSG: "+response);
			if(buffer.hasRemaining()){
				buffer.compact();
			}
			else{
				buffer.clear();
			}
			request = clientInput.readLine();
			channel.write(ByteBuffer.wrap(request.getBytes())).get();
		}
	}

	public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
		NIO2_AIO_Client1 client = new NIO2_AIO_Client1();
		client.init();
		client.start();
	}

}





查看评论

JAVA NIO2模式之Proactor( JDK7 AIO异步网络IO初探)

按照《Unix网络编程》的划分,IO模型可以分为:阻塞IO、非阻塞IO、IO复用、信号驱动IO和异步IO,按照POSIX标准来划分只分为两类:同步IO和异步IO。如何区分呢?首先一个IO操作其实分成了...
  • ajian005
  • ajian005
  • 2014-01-09 22:26:06
  • 3259

java中IO、NIO、AIO(NIO2.0)的学习

java中的IO 传统的IO 我们通常所说的传统IO编程就是同步阻塞式的I/O编程,也就是一个Socket和一个Client的端到端的通信过程,我们启动Socket端的时候,Socket会调用acce...
  • a347911
  • a347911
  • 2016-12-13 16:30:31
  • 2869

Java中的BIO、NIO、AIO(NIO2)

在高性能的IO体系设计中,有几个名词概念常常会使我们感到迷惑不解。具体如下:  序号 问题 1 什么是同步? 2 什么是异步? 3 什么是阻塞? 4 什么是非阻塞? 5 什...
  • zhangzeyuaaa
  • zhangzeyuaaa
  • 2016-01-14 21:50:15
  • 8742

java7 AIO / NIO 2 小记

JSR 203 习惯上称为 NIO.2,主要包括新的: 异步 I/O(简称 AIO);Multicase 多播;Stream Control Transport Protocol(SCTP);文件系统...
  • conquer0715
  • conquer0715
  • 2016-03-02 16:21:20
  • 5599

AIO编程(NIO2.0)及代码实现

AIO编程    NIO 2.0引入了新的异步通道的概念,并提供了异步文件通道和异步套接字通道的实现。    异步的套接字通道时真正的异步非阻塞I/O,对应于UNIX网络编程中的事件驱动I/O(AIO...
  • wanbf123
  • wanbf123
  • 2017-09-21 17:40:26
  • 244

Java并发编程-Executor框架之Callable和Future接口

在上一篇文章中我们已经了解了Executor框架进行线程管理,这篇文章将学习Executor框架的另一个特性,我们知道执行Runnable任务是没有返回值得,但Executor可以运行并发任务并获得返...
  • chenchaofuck1
  • chenchaofuck1
  • 2016-06-07 20:58:57
  • 3925

Java并发编程实践:Callable异步回调Future、FutureTask用法

Callable接口类似于Runnable,从名字就可以看出来了,但是Runnable不会返回结果,并且无法抛出返回结果的异常,而Callable功能更强大一些,被线程执行后,可以返回值,这个返回值可...
  • boonya
  • boonya
  • 2017-04-05 15:11:04
  • 3495

Java并发编程:Callable、Future和FutureTask原理解析

返回结果的任务Callable与FutureExecutor框架使用Runnable作为其基本的任务表示形式。Runnable是一种有很大局限的抽象,它不能返回一个值或抛出一个受检查的异常。Runna...
  • codershamo
  • codershamo
  • 2016-07-13 20:00:41
  • 6201

Java 多线程 callable future实例

Java 多线程 callable future实例
  • Tc_To_Top
  • Tc_To_Top
  • 2016-09-17 20:41:11
  • 1125

JAVA 并发编程-返回执行结果(Callable和Future)(九)

启动一个线程不论使用Thread或者Runnable的时候,都是没有返回结果的。也就是说Thread和Runnable的run()方法必须没有返回值。   public void run(){} 解决...
  • hejingyuan6
  • hejingyuan6
  • 2015-07-30 10:12:38
  • 4350
    个人资料
    持之以恒
    等级:
    访问量: 23万+
    积分: 6097
    排名: 5152
    最新评论