Java network programming - AIO programming

Keywords: Java Programming socket

1, Introduction

In AIO programming, the concept of asynchronous channel is introduced on the basis of NIO, and the realization of asynchronous file and asynchronous socket channel is provided, so as to realize asynchronous non blocking in the true sense. NIO is only non blocking rather than asynchronous. AIO does not need to poll the registered channel through the multiplexer to realize asynchronous reading and writing, This simplifies the NIO programming model. It can also be called NIO2.0. This mode is really our asynchronous non blocking model

     AsynchronousServerSocketChannel

     AsynchronousSocketChannel


2, Code example

package com.east.aio;

import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
	//Thread pool
	private ExecutorService executorService;
	//Thread group
	private AsynchronousChannelGroup threadGroup;
	//Server channel
	public AsynchronousServerSocketChannel assc;
	
	public Server(int port) {
		try {
			//Create a buffer pool
			executorService = Executors.newCachedThreadPool();
			//Create thread group
			threadGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService, 1);
			//Create server channel
			assc = AsynchronousServerSocketChannel.open(threadGroup);                 //Asynchronous non blocking
			//Binding
			assc.bind(new InetSocketAddress(port));
			
			System.out.println("Server Start , Port : " + port);
			//Block
			assc.accept(this, new ServerCompletionHandler());     //Get asynchronous information from the client
			//Keep blocking, don't let the service stop
			Thread.sleep(Integer.MAX_VALUE);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Server server = new Server(8788);
	}

}

package com.east.aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;

public class ServerCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, Server> {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
 
	}

	@Override
	public void completed(AsynchronousSocketChannel asc, Server attachment) {
		// TODO Auto-generated method stub
		//When the next client accesses, the server's accept() method is called directly, which is executed repeatedly to ensure that multiple clients can block
		attachment.assc.accept(attachment,this);
		read(asc);
	}

	@Override
	public void failed(Throwable exc, Server attachment) {
		// TODO Auto-generated method stub
		exc.printStackTrace();
	}

	public void read(final AsynchronousSocketChannel asc){
		//Read data
		ByteBuffer buf = ByteBuffer.allocate(1024);
		asc.read(buf, buf, new CompletionHandler<Integer, ByteBuffer>() {

			@Override
			public void completed(Integer result, ByteBuffer attachment) {
				// TODO Auto-generated method stub
				//After reading, reset the identification bit
				attachment.flip();
				//Get bytes read
				System.out.println("Server ->" + "The length of data received from the client is :" + result);
				//Get read data
				String resultData = new String(attachment.array()).trim();
				System.out.println("Server ->" + "The data information received from the client is:" + resultData);
				String response = "Server response,Received data from client: "+ resultData;
				write(asc, response);
			}

			@Override
			public void failed(Throwable exc, ByteBuffer attachment) {
				// TODO Auto-generated method stub
				exc.printStackTrace();
			}
		});
	}
	
	private void write(AsynchronousSocketChannel asc,String response){
		try {
			ByteBuffer buf = ByteBuffer.allocate(1024);
			buf.put(response.getBytes());                //Write data to ByteBuffer
			buf.flip();                                  //reset
			asc.write(buf).get();                        //Start a new thread to write
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

package com.east.aio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;

public class Client implements Runnable {

	private AsynchronousSocketChannel asc;
	
	public Client() throws Exception{
	  asc = AsynchronousSocketChannel.open();
	}
	
	public void connect(){
		asc.connect(new InetSocketAddress("127.0.0.1", 8788));
	}
	
	public void write(String request){
		try {
			asc.write(ByteBuffer.wrap(request.getBytes())).get();
			read();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void read(){
		ByteBuffer buf = ByteBuffer.allocate(1024);
		try {
			asc.read(buf).get();
			buf.flip();
			byte[] respByte = new byte[buf.remaining()];
			buf.get(respByte);
			System.out.println(new String(respByte,"utf-8").trim());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
       while(true){
    	   
       }
	}

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
       Client c1 = new Client();
       c1.connect();
       
       Client c2 = new Client();
       c2.connect();
       
       Client c3 = new Client();
       c3.connect();
       
       new Thread(c1, "c1").start();
       new Thread(c2, "c2").start();
       new Thread(c3, "c3").start();
       
       Thread.sleep(1000);
       
       c1.write("c1 aaa");
       c2.write("c2 bbbb");
       c3.write("c3 ccccc");
	}

}

Posted by trial_end_error on Sat, 02 May 2020 08:54:33 -0700