JDK7 AIO (non-blocking io) to achieve large concurrency tcpserver and tcpclient

Source: Internet
Author: User


JDK7 Although has been released for some time, but helpless, AIO related introduction, especially rely on the introduction of way is too little. The brothers spent some time in sorting the book, hoping to help learner.

Epoll became the first choice for developing a large concurrent Web server under Linux for years, and the Java world didn't use this feature until the AIO of JDK 7 came into being. Hey. But it's not too late to mend, so look below to develop a simple TCP server and TCP Client with AIO.

1. The following code structure consists of 6 files


2. Demo Test results:



3. TCP Server consists of three files.

Aiotcpserver is the main file

Aioaccepthandler is responsible for receiving connections, using recursive models

Aioreadhandler is responsible for receiving client data, still asynchronous

3.1 Aiotcpserver.java

Package server;

Import java.net.InetSocketAddress;
Import Java.nio.channels.AsynchronousChannelGroup;
Import Java.nio.channels.AsynchronousServerSocketChannel;
Import Java.nio.channels.AsynchronousSocketChannel;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future;

public class Aiotcpserver implements Runnable {
Private Asynchronouschannelgroup Asyncchannelgroup;
Private Asynchronousserversocketchannel listener;

public aiotcpserver (int port) throws Exception {
Executorservice executor = Executors.newfixedthreadpool (20);
Asyncchannelgroup = Asynchronouschannelgroup.withthreadpool (executor);
Listener = Asynchronousserversocketchannel.open (Asyncchannelgroup). bind (New Inetsocketaddress (port));
}

public void Run () {
try {

Aioaccepthandler Accepthandler = new Aioaccepthandler ();
Listener.accept (Listener, New Aioaccepthandler ());
Thread.Sleep (400000);
catch (Exception e) {
E.printstacktrace ();
finally {
System.out.println ("finished server");
}
}

public static void Main (String ... args) throws Exception {
Aiotcpserver Server = new Aiotcpserver (9008);
New Thread (server). Start ();
}
}

3.2 Aioaccepthandler.java

Package server;

Import java.io.IOException;
Import Java.nio.ByteBuffer;
Import Java.nio.channels.AsynchronousServerSocketChannel;
Import Java.nio.channels.AsynchronousSocketChannel;
Import Java.nio.channels.CompletionHandler;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.Future;

public class Aioaccepthandler implements Completionhandler {
public void cancelled (Asynchronousserversocketchannel attachment) {
System.out.println ("cancelled");
}

public void completed (Asynchronoussocketchannel socket, Asynchronousserversocketchannel attachment) {
try {
System.out.println ("aioaccepthandler.completed called");
Attachment.accept (attachment, this);
SYSTEM.OUT.PRINTLN ("Have Client connection:" + socket.getremoteaddress (). toString ());
Startread (socket);
catch (IOException e) {
E.printstacktrace ();
}
}

public void failed (Throwable exc, asynchronousserversocketchannel attachment) {
Exc.printstacktrace ();
}

public void Startread (Asynchronoussocketchannel socket) {
Bytebuffer Clientbuffer = bytebuffer.allocate (1024);
Socket.read (Clientbuffer, Clientbuffer, new Aioreadhandler (socket));
try {

catch (Exception e) {
E.printstacktrace ();
}
}
}

3.3 Aioreadhandler.java

Package server;

Import java.io.IOException;
Import Java.nio.ByteBuffer;
Import Java.nio.channels.AsynchronousSocketChannel;
Import Java.nio.channels.CompletionHandler;
Import java.nio.charset.CharacterCodingException;
Import Java.nio.charset.Charset;
Import Java.nio.charset.CharsetDecoder;

public class Aioreadhandler implements Completionhandler {
Private Asynchronoussocketchannel socket;

Public Aioreadhandler (Asynchronoussocketchannel socket) {
This.socket = socket;
}

public void cancelled (Bytebuffer attachment) {
System.out.println ("cancelled");
}

Private Charsetdecoder decoder = Charset.forname ("GBK"). Newdecoder ();

public void completed (Integer i, Bytebuffer buf) {
if (i > 0) {
Buf.flip ();
try {
System.out.println ("Received" + socket.getremoteaddress (). toString () + "message:" + Decoder.decode (BUF));
Buf.compact ();
catch (Charactercodingexception e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}
Socket.read (buf, buf, this);
else if (i = = 1) {
try {
SYSTEM.OUT.PRINTLN ("Client disconnected:" + socket.getremoteaddress (). toString ());

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.