|
| 1 | +package com.msj.network.aio; |
| 2 | + |
| 3 | +import java.nio.ByteBuffer; |
| 4 | +import java.nio.channels.AsynchronousSocketChannel; |
| 5 | +import java.nio.channels.CompletionHandler; |
| 6 | +import java.util.concurrent.ExecutionException; |
| 7 | + |
| 8 | +public class ServerCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, Server> { |
| 9 | + |
| 10 | + @Override |
| 11 | + public void completed(AsynchronousSocketChannel asc, Server attachment) { |
| 12 | + //当有下一个客户端接入的时候 直接调用Server的accept方法,这样反复执行下去,保证多个客户端都可以阻塞 |
| 13 | + attachment.assc.accept(attachment, this); |
| 14 | + read(asc); |
| 15 | + } |
| 16 | + |
| 17 | + private void read(final AsynchronousSocketChannel asc) { |
| 18 | + //读取数据 |
| 19 | + ByteBuffer buf = ByteBuffer.allocate(1024); |
| 20 | + asc.read(buf, buf, new CompletionHandler<Integer, ByteBuffer>() { |
| 21 | + @Override |
| 22 | + public void completed(Integer resultSize, ByteBuffer attachment) { |
| 23 | + //进行读取之后,重置标识位 |
| 24 | + attachment.flip(); |
| 25 | + //获得读取的字节数 |
| 26 | + System.out.println("Server -> " + "收到客户端的数据长度为:" + resultSize); |
| 27 | + //获取读取的数据 |
| 28 | + String resultData = new String(attachment.array()).trim(); |
| 29 | + System.out.println("Server -> " + "收到客户端的数据信息为:" + resultData); |
| 30 | + String response = "服务器响应, 收到了客户端发来的数据: " + resultData; |
| 31 | + write(asc, response); |
| 32 | + } |
| 33 | + @Override |
| 34 | + public void failed(Throwable exc, ByteBuffer attachment) { |
| 35 | + exc.printStackTrace(); |
| 36 | + } |
| 37 | + }); |
| 38 | + } |
| 39 | + |
| 40 | + private void write(AsynchronousSocketChannel asc, String response) { |
| 41 | + try { |
| 42 | + ByteBuffer buf = ByteBuffer.allocate(1024); |
| 43 | + buf.put(response.getBytes()); |
| 44 | + buf.flip(); |
| 45 | + asc.write(buf).get(); |
| 46 | + } catch (InterruptedException e) { |
| 47 | + e.printStackTrace(); |
| 48 | + } catch (ExecutionException e) { |
| 49 | + e.printStackTrace(); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + @Override |
| 54 | + public void failed(Throwable exc, Server attachment) { |
| 55 | + exc.printStackTrace(); |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments