java nio java 7,java-nio基础-7-异步io

package com.scn7th.asynchronousIO;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.net.SocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.AsynchronousServerSocketChannel;

import java.nio.channels.AsynchronousSocketChannel;

import java.nio.channels.CompletionHandler;@Slf4jpublic class MyAsynchronousServerSocketChannel {

public static void listen() throws IOException {

AsynchronousServerSocketChannel serverSocketChannel =

AsynchronousServerSocketChannel.open();

serverSocketChannel.bind(new InetSocketAddress(8077));

Attachment attachment = new Attachment();

attachment.serverChannel = serverSocketChannel;

serverSocketChannel.accept(attachment, new ConnectionHandler());

try

{

Thread.currentThread().join();

}

catch (InterruptedException ie)

{

System.out.println("Server terminating");

}

}

private static class Attachment{

private AsynchronousServerSocketChannel serverChannel;

private AsynchronousSocketChannel clientChannel;

public boolean isReadMode;

public ByteBuffer buffer;

public SocketAddress clientAddress;

}

private static class ConnectionHandler implements CompletionHandlerAsynchronousSocketChannel, Attachment{

@Override

public void completed(AsynchronousSocketChannel

clientChannel, Attachment attachment) {

SocketAddress clientAddr = null;

try {

clientAddr = clientChannel.getRemoteAddress();

} catch (IOException e) {

e.printStackTrace();

}

log.info("Accepted connection from :{}", clientAddr);

//calls accept() on the server socket channel with

the passed Attachment object and a reference to the current

completion handler

//as arguments. This call allows the server to respond to the next

incoming connection.

attachment.serverChannel.accept(attachment, this);

Attachment newAttachment = new Attachment();

newAttachment.serverChannel = attachment.serverChannel;

newAttachment.clientChannel = clientChannel;

newAttachment.isReadMode = true;

newAttachment.clientAddress = clientAddr;

newAttachment.buffer = ByteBuffer.allocate(2048);

ReadWriteHandler readWriteHandler =

new ReadWriteHandler();

clientChannel.read(newAttachment.buffer, newAttachment, readWriteHandler);

}

@Override

public void failed(Throwable exc, Attachment attachment) {

System.out.println("Failed to connect...");

}

}

private static class ReadWriteHandler implements CompletionHandlerInteger, Attachment {

@Override

public void completed(Integer result, Attachment attachment) {

if(result == -1) {

try {

attachment.clientChannel.close();

System.out.printf("Stopped listening to client

%s%n",

attachment.clientAddress);

} catch (IOException e) {

e.printStackTrace();

}

return;

}

else {

//readMode下首先读取了数据,然后又异步向client写了原buffer。此时为readMode=false,也就是不会接收新的socket读取,除非异步完成了向client回写buffer

if(attachment.isReadMode) {

attachment.buffer.flip();

int limit = attachment.buffer.limit();

byte[] bytes = new byte[limit];

attachment.buffer.get(bytes, 0, limit);

log.info("Client at {} sends message: {}",attachment.clientAddress, new String(bytes));

attachment.isReadMode = false;

attachment.buffer.rewind();

attachment.clientChannel.write(attachment.buffer, attachment, this);

}

else {

log.info("---------write");

attachment.isReadMode = true;

attachment.buffer.clear();

attachment.clientChannel.read(attachment.buffer, attachment, this);

}

}

}

@Override

public void failed(Throwable exc, Attachment attachment) {

System.out.println("Failed to read/write...");

}

}

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

listen();

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值