Java AIO方法实现TCP Socket服务器支持多客户端的例子

代码:

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;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class AIOServer {
    public final static int PORT = 9888;
    private AsynchronousServerSocketChannel server;

    public AIOServer() throws IOException {
        System.out.println("APP Start, ThreadID = "+Thread.currentThread().getId());
        server = AsynchronousServerSocketChannel.open().bind(
                new InetSocketAddress(PORT)
        );
    }

    public void startWithCompletionHandler() throws InterruptedException, ExecutionException,
            TimeoutException {
        System.out.println("Server Listenning ..., Port = " + PORT);
        //注册事件和事件完成后的处理器
        server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            final ByteBuffer buffer = ByteBuffer.allocate(1024);

            public void completed(AsynchronousSocketChannel socketChannel, Object attachment) {
                System.out.println("Accpet Completed,  ThreadID = "+Thread.currentThread().getId()+", socketChannel = "+socketChannel.hashCode());
                CompletionHandler<Integer,ByteBuffer> handler=new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer readLen, ByteBuffer attachment) {
                        System.out.println("Read Completed, ThreadID = "+Thread.currentThread().getId()+", socketChannel = "+socketChannel.hashCode());
                        if (readLen < 0){
                            System.out.println("Read Error!"); //经测试,如果在读取的过程中连接断开,readLen会小于0
                            return;
                        }
                        attachment.flip();
                        System.out.println("Read Success, Data = "+new String(attachment.array()));
                        socketChannel.read(buffer, buffer, this);  //执行下一次read,否则本Socket只能读取一次
                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {
                        System.out.println("Read Failed!");
                    }
                };
                socketChannel.read(buffer, buffer, handler);
                server.accept(null, this);  //执行下一次Accept,否则本Socket服务器只能连接一次
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                System.out.println("Accept Failed : " + exc);
            }
        });

        // 主线程继续自己的行为
        while(true) {
            Thread.sleep(10);
        }
    }

    public static void main(String[] args) throws Exception {
        new AIOServer().startWithCompletionHandler();
    }
}

运行效果:

注:图中Read Error 是客户端断开TCP连接时的输出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值