├── .classpath
├── .project
├── .settings
├── org.eclipse.jdt.core.prefs
└── org.eclipse.m2e.core.prefs
├── README.md
├── pom.xml
└── src
└── com
└── anxpp
└── io
├── calculator
├── aio
│ ├── Test.java
│ ├── client
│ │ ├── AsyncClientHandler.java
│ │ ├── Client.java
│ │ ├── ReadHandler.java
│ │ └── WriteHandler.java
│ └── server
│ │ ├── AcceptHandler.java
│ │ ├── AsyncServerHandler.java
│ │ ├── ReadHandler.java
│ │ └── Server.java
├── bio
│ ├── Client.java
│ ├── ServerBetter.java
│ ├── ServerHandler.java
│ ├── ServerNormal.java
│ └── Test.java
├── netty
│ ├── Client.java
│ ├── ClientHandler.java
│ ├── Server.java
│ └── ServerHandler.java
└── nio
│ ├── Client.java
│ ├── ClientHandle.java
│ ├── Server.java
│ ├── ServerHandle.java
│ └── Test.java
└── utils
└── Calculator.java
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Java IO
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 | org.eclipse.m2e.core.maven2Builder
15 |
16 |
17 |
18 |
19 |
20 | org.eclipse.m2e.core.maven2Nature
21 | org.eclipse.jdt.core.javanature
22 |
23 |
24 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
12 | org.eclipse.jdt.core.compiler.source=1.8
13 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.m2e.core.prefs:
--------------------------------------------------------------------------------
1 | activeProfiles=
2 | eclipse.preferences.version=1
3 | resolveWorkspaceProjects=true
4 | version=1
5 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Java-IO
2 | https://blog.csdn.net/anxpp/article/details/51512200
3 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | anxpp.com
5 | JavaIO
6 | 0.0.1-SNAPSHOT
7 |
8 | src
9 |
10 |
11 | maven-compiler-plugin
12 | 3.3
13 |
14 | 1.8
15 | 1.8
16 |
17 |
18 |
19 |
20 |
21 |
22 | io.netty
23 | netty-all
24 | 4.1.4.Final
25 |
26 |
27 |
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/aio/Test.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/aio/Test.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/aio/client/AsyncClientHandler.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/aio/client/AsyncClientHandler.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/aio/client/Client.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/aio/client/Client.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/aio/client/ReadHandler.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/aio/client/ReadHandler.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/aio/client/WriteHandler.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/aio/client/WriteHandler.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/aio/server/AcceptHandler.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/aio/server/AcceptHandler.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/aio/server/AsyncServerHandler.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/aio/server/AsyncServerHandler.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/aio/server/ReadHandler.java:
--------------------------------------------------------------------------------
1 | package com.anxpp.io.calculator.aio.server;
2 | import java.io.IOException;
3 | import java.io.UnsupportedEncodingException;
4 | import java.nio.ByteBuffer;
5 | import java.nio.channels.AsynchronousSocketChannel;
6 | import java.nio.channels.CompletionHandler;
7 | import com.anxpp.io.utils.Calculator;
8 | public class ReadHandler implements CompletionHandler {
9 | //���ڶ�ȡ�����Ϣ�ͷ���Ӧ��
10 | private AsynchronousSocketChannel channel;
11 | public ReadHandler(AsynchronousSocketChannel channel) {
12 | this.channel = channel;
13 | }
14 | //��ȡ����Ϣ��Ĵ���
15 | @Override
16 | public void completed(Integer result, ByteBuffer attachment) {
17 | //flip����
18 | attachment.flip();
19 | //����
20 | byte[] message = new byte[attachment.remaining()];
21 | attachment.get(message);
22 | try {
23 | String expression = new String(message, "UTF-8");
24 | System.out.println("�������յ���Ϣ: " + expression);
25 | String calrResult = null;
26 | try{
27 | calrResult = Calculator.Instance.cal(expression).toString();
28 | }catch(Exception e){
29 | calrResult = "�������" + e.getMessage();
30 | }
31 | //��ͻ��˷�����Ϣ
32 | doWrite(calrResult);
33 | } catch (UnsupportedEncodingException e) {
34 | e.printStackTrace();
35 | }
36 | }
37 | //������Ϣ
38 | private void doWrite(String result) {
39 | byte[] bytes = result.getBytes();
40 | ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
41 | writeBuffer.put(bytes);
42 | writeBuffer.flip();
43 | //�첽д���� ������ǰ���readһ��
44 | channel.write(writeBuffer, writeBuffer,new CompletionHandler() {
45 | @Override
46 | public void completed(Integer result, ByteBuffer buffer) {
47 | //���û�з����꣬�ͼ�������ֱ�����
48 | if (buffer.hasRemaining())
49 | channel.write(buffer, buffer, this);
50 | else{
51 | //�����µ�Buffer
52 | ByteBuffer readBuffer = ByteBuffer.allocate(1024);
53 | //�첽�� ����������Ϊ������Ϣ�ص���ҵ��Handler
54 | channel.read(readBuffer, readBuffer, new ReadHandler(channel));
55 | }
56 | }
57 | @Override
58 | public void failed(Throwable exc, ByteBuffer attachment) {
59 | try {
60 | channel.close();
61 | } catch (IOException e) {
62 | }
63 | }
64 | });
65 | }
66 | @Override
67 | public void failed(Throwable exc, ByteBuffer attachment) {
68 | try {
69 | this.channel.close();
70 | } catch (IOException e) {
71 | e.printStackTrace();
72 | }
73 | }
74 | }
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/aio/server/Server.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/aio/server/Server.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/bio/Client.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/bio/Client.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/bio/ServerBetter.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/bio/ServerBetter.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/bio/ServerHandler.java:
--------------------------------------------------------------------------------
1 | package com.anxpp.io.calculator.bio;
2 | import java.io.BufferedReader;
3 | import java.io.IOException;
4 | import java.io.InputStreamReader;
5 | import java.io.PrintWriter;
6 | import java.net.Socket;
7 |
8 | import com.anxpp.io.utils.Calculator;
9 | /**
10 | * �ͻ����߳�
11 | * @author yangtao__anxpp.com
12 | * ���ڴ���һ���ͻ��˵�Socket��·
13 | */
14 | public class ServerHandler implements Runnable{
15 | private Socket socket;
16 | public ServerHandler(Socket socket) {
17 | this.socket = socket;
18 | }
19 | @Override
20 | public void run() {
21 | BufferedReader in = null;
22 | PrintWriter out = null;
23 | try{
24 | in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
25 | out = new PrintWriter(socket.getOutputStream(),true);
26 | String expression;
27 | String result;
28 | while(true){
29 | //ͨ��BufferedReader��ȡһ��
30 | //����Ѿ�����������β��������null,�˳�ѭ��
31 | //����õ��ǿ�ֵ���ͳ��Լ�����������
32 | if((expression = in.readLine())==null) break;
33 | System.out.println("�������յ���Ϣ��" + expression);
34 | try{
35 | result = Calculator.Instance.cal(expression).toString();
36 | }catch(Exception e){
37 | result = "�������" + e.getMessage();
38 | }
39 | out.println(result);
40 | }
41 | }catch(Exception e){
42 | e.printStackTrace();
43 | }finally{
44 | //һЩ��Ҫ��������
45 | if(in != null){
46 | try {
47 | in.close();
48 | } catch (IOException e) {
49 | e.printStackTrace();
50 | }
51 | in = null;
52 | }
53 | if(out != null){
54 | out.close();
55 | out = null;
56 | }
57 | if(socket != null){
58 | try {
59 | socket.close();
60 | } catch (IOException e) {
61 | e.printStackTrace();
62 | }
63 | socket = null;
64 | }
65 | }
66 | }
67 | }
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/bio/ServerNormal.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/bio/ServerNormal.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/bio/Test.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/bio/Test.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/netty/Client.java:
--------------------------------------------------------------------------------
1 | package com.anxpp.io.calculator.netty;
2 |
3 | import io.netty.bootstrap.Bootstrap;
4 | import io.netty.channel.ChannelFuture;
5 | import io.netty.channel.ChannelInitializer;
6 | import io.netty.channel.ChannelOption;
7 | import io.netty.channel.EventLoopGroup;
8 | import io.netty.channel.nio.NioEventLoopGroup;
9 | import io.netty.channel.socket.SocketChannel;
10 | import io.netty.channel.socket.nio.NioSocketChannel;
11 |
12 | import java.util.Scanner;
13 |
14 | public class Client implements Runnable{
15 |
16 | static ClientHandler client = new ClientHandler();
17 |
18 | public static void main(String[] args) throws Exception {
19 | new Thread(new Client()).start();
20 | @SuppressWarnings("resource")
21 | Scanner scanner = new Scanner(System.in);
22 | while(client.sendMsg(scanner.nextLine()));
23 | }
24 |
25 | @Override
26 | public void run() {
27 | String host = "127.0.0.1";
28 | int port = 9090;
29 | EventLoopGroup workerGroup = new NioEventLoopGroup();
30 | try {
31 | Bootstrap b = new Bootstrap();
32 | b.group(workerGroup);
33 | b.channel(NioSocketChannel.class);
34 | b.option(ChannelOption.SO_KEEPALIVE, true);
35 | b.handler(new ChannelInitializer() {
36 | @Override
37 | public void initChannel(SocketChannel ch) throws Exception {
38 | ch.pipeline().addLast(client);
39 | }
40 | });
41 | ChannelFuture f = b.connect(host, port).sync();
42 | f.channel().closeFuture().sync();
43 | } catch (InterruptedException e) {
44 | e.printStackTrace();
45 | } finally {
46 | workerGroup.shutdownGracefully();
47 | }
48 | }
49 | }
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/netty/ClientHandler.java:
--------------------------------------------------------------------------------
1 | package com.anxpp.io.calculator.netty;
2 |
3 | import io.netty.buffer.ByteBuf;
4 | import io.netty.buffer.Unpooled;
5 | import io.netty.channel.ChannelHandlerContext;
6 | import io.netty.channel.ChannelInboundHandlerAdapter;
7 |
8 | import java.io.UnsupportedEncodingException;
9 |
10 | public class ClientHandler extends ChannelInboundHandlerAdapter {
11 |
12 | ChannelHandlerContext ctx;
13 | /**
14 | * tcp链路简历成功后调用
15 | */
16 | @Override
17 | public void channelActive(ChannelHandlerContext ctx) throws Exception {
18 | this.ctx = ctx;
19 | sendMsg("客户端消息");
20 | }
21 |
22 | public boolean sendMsg(String msg){
23 | System.out.println("客户端发送消息:"+msg);
24 | byte[] req = msg.getBytes();
25 | ByteBuf m = Unpooled.buffer(req.length);
26 | m.writeBytes(req);
27 | ctx.writeAndFlush(m);
28 | return msg.equals("q")?false:true;
29 | }
30 |
31 | /**
32 | * 收到服务器消息后调用
33 | * @throws UnsupportedEncodingException
34 | */
35 | @Override
36 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
37 | ByteBuf buf = (ByteBuf) msg;
38 | byte[] req = new byte[buf.readableBytes()];
39 | buf.readBytes(req);
40 | String body = new String(req,"utf-8");
41 | System.out.println("服务器消息:"+body);
42 | }
43 | /**
44 | * 发生异常时调用
45 | */
46 | @Override
47 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
48 | cause.printStackTrace();
49 | ctx.close();
50 | }
51 | }
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/netty/Server.java:
--------------------------------------------------------------------------------
1 | package com.anxpp.io.calculator.netty;
2 | import io.netty.bootstrap.ServerBootstrap;
3 |
4 | import io.netty.channel.ChannelFuture;
5 | import io.netty.channel.ChannelInitializer;
6 | import io.netty.channel.ChannelOption;
7 | import io.netty.channel.EventLoopGroup;
8 | import io.netty.channel.nio.NioEventLoopGroup;
9 | import io.netty.channel.socket.SocketChannel;
10 | import io.netty.channel.socket.nio.NioServerSocketChannel;
11 |
12 | public class Server {
13 |
14 | private int port;
15 |
16 | public Server(int port) {
17 | this.port = port;
18 | }
19 |
20 | public void run() throws Exception {
21 | EventLoopGroup bossGroup = new NioEventLoopGroup();
22 | EventLoopGroup workerGroup = new NioEventLoopGroup();
23 | try {
24 | ServerBootstrap b = new ServerBootstrap();
25 | b.group(bossGroup, workerGroup)
26 | .channel(NioServerSocketChannel.class)
27 | .option(ChannelOption.SO_BACKLOG, 1024)
28 | .childOption(ChannelOption.SO_KEEPALIVE, true)
29 | .childHandler(new ChannelInitializer() {
30 | @Override
31 | public void initChannel(SocketChannel ch) throws Exception {
32 | ch.pipeline().addLast(new ServerHandler());
33 | }
34 | });
35 |
36 | ChannelFuture f = b.bind(port).sync();
37 | System.out.println("服务器开启:"+port);
38 | f.channel().closeFuture().sync();
39 | } finally {
40 | workerGroup.shutdownGracefully();
41 | bossGroup.shutdownGracefully();
42 | }
43 | }
44 |
45 | public static void main(String[] args) throws Exception {
46 | int port;
47 | if (args.length > 0) {
48 | port = Integer.parseInt(args[0]);
49 | } else {
50 | port = 9090;
51 | }
52 | new Server(port).run();
53 | }
54 | }
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/netty/ServerHandler.java:
--------------------------------------------------------------------------------
1 | package com.anxpp.io.calculator.netty;
2 |
3 | import io.netty.buffer.ByteBuf;
4 | import io.netty.buffer.Unpooled;
5 | import io.netty.channel.ChannelHandlerContext;
6 | import io.netty.channel.ChannelInboundHandlerAdapter;
7 |
8 | import java.io.UnsupportedEncodingException;
9 |
10 | import com.anxpp.io.utils.Calculator;
11 |
12 | /**
13 | * Handles a server-side channel.
14 | */
15 | public class ServerHandler extends ChannelInboundHandlerAdapter {
16 |
17 | /**
18 | * 收到客户端消息
19 | * @throws UnsupportedEncodingException
20 | */
21 | @Override
22 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
23 | ByteBuf in = (ByteBuf) msg;
24 | byte[] req = new byte[in.readableBytes()];
25 | in.readBytes(req);
26 | String body = new String(req,"utf-8");
27 | System.out.println("收到客户端消息:"+body);
28 | String calrResult = null;
29 | try{
30 | calrResult = Calculator.Instance.cal(body).toString();
31 | }catch(Exception e){
32 | calrResult = "错误的表达式:" + e.getMessage();
33 | }
34 | ctx.write(Unpooled.copiedBuffer(calrResult.getBytes()));
35 | }
36 |
37 | @Override
38 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
39 | ctx.flush();
40 | }
41 |
42 | /**
43 | * 异常处理
44 | */
45 | @Override
46 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
47 | cause.printStackTrace();
48 | ctx.close();
49 | }
50 | }
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/nio/Client.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/nio/Client.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/nio/ClientHandle.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/nio/ClientHandle.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/nio/Server.java:
--------------------------------------------------------------------------------
1 | package com.anxpp.io.calculator.nio;
2 | public class Server {
3 | private static int DEFAULT_PORT = 12345;
4 | private static ServerHandle serverHandle;
5 | public static void start(){
6 | start(DEFAULT_PORT);
7 | }
8 | public static synchronized void start(int port){
9 | if(serverHandle!=null)
10 | serverHandle.stop();
11 | serverHandle = new ServerHandle(port);
12 | new Thread(serverHandle,"Server").start();
13 | }
14 | public static void main(String[] args){
15 | start();
16 | }
17 | }
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/nio/ServerHandle.java:
--------------------------------------------------------------------------------
1 | package com.anxpp.io.calculator.nio;
2 | import java.io.IOException;
3 | import java.net.InetSocketAddress;
4 | import java.nio.ByteBuffer;
5 | import java.nio.channels.SelectionKey;
6 | import java.nio.channels.Selector;
7 | import java.nio.channels.ServerSocketChannel;
8 | import java.nio.channels.SocketChannel;
9 | import java.util.Iterator;
10 | import java.util.Set;
11 |
12 | import com.anxpp.io.utils.Calculator;
13 | /**
14 | * NIO�����
15 | * @author yangtao__anxpp.com
16 | * @version 1.0
17 | */
18 | public class ServerHandle implements Runnable{
19 | private Selector selector;
20 | private ServerSocketChannel serverChannel;
21 | private volatile boolean started;
22 | /**
23 | * ���췽��
24 | * @param port ָ��Ҫ�����Ķ˿ں�
25 | */
26 | public ServerHandle(int port) {
27 | try{
28 | //����ѡ����
29 | selector = Selector.open();
30 | //����ͨ��
31 | serverChannel = ServerSocketChannel.open();
32 | //���Ϊ true�����ͨ��������������ģʽ�����Ϊ false�����ͨ���������ڷ�����ģʽ
33 | serverChannel.configureBlocking(false);//����������ģʽ
34 | //�˿� backlog��Ϊ1024
35 | serverChannel.socket().bind(new InetSocketAddress(port),1024);
36 | //�����ͻ�����������
37 | serverChannel.register(selector, SelectionKey.OP_ACCEPT);
38 | //��Ƿ������ѿ���
39 | started = true;
40 | System.out.println("���������������˿ںţ�" + port);
41 | }catch(IOException e){
42 | e.printStackTrace();
43 | System.exit(1);
44 | }
45 | }
46 | public void stop(){
47 | started = false;
48 | }
49 | @Override
50 | public void run() {
51 | //ѭ������selector
52 | while(started){
53 | try{
54 | //�����Ƿ��ж�д�¼�������selectorÿ��1s������һ��
55 | selector.select(1000);
56 | //����,ֻ�е�����һ��ע����¼�������ʱ��Ż����.
57 | // selector.select();
58 | Set keys = selector.selectedKeys();
59 | Iterator it = keys.iterator();
60 | SelectionKey key = null;
61 | while(it.hasNext()){
62 | key = it.next();
63 | it.remove();
64 | try{
65 | handleInput(key);
66 | }catch(Exception e){
67 | if(key != null){
68 | key.cancel();
69 | if(key.channel() != null){
70 | key.channel().close();
71 | }
72 | }
73 | }
74 | }
75 | }catch(Throwable t){
76 | t.printStackTrace();
77 | }
78 | }
79 | //selector�رպ���Զ��ͷ�����������Դ
80 | if(selector != null)
81 | try{
82 | selector.close();
83 | }catch (Exception e) {
84 | e.printStackTrace();
85 | }
86 | }
87 | private void handleInput(SelectionKey key) throws IOException{
88 | if(key.isValid()){
89 | //�����½����������Ϣ
90 | if(key.isAcceptable()){
91 | ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
92 | //ͨ��ServerSocketChannel��accept����SocketChannelʵ��
93 | //��ɸò�����ζ�����TCP�������֣�TCP������·��ʽ����
94 | SocketChannel sc = ssc.accept();
95 | //������������
96 | sc.configureBlocking(false);
97 | //ע��Ϊ��
98 | sc.register(selector, SelectionKey.OP_READ);
99 | }
100 | //����Ϣ
101 | if(key.isReadable()){
102 | SocketChannel sc = (SocketChannel) key.channel();
103 | //����ByteBuffer��������һ��1M�Ļ�����
104 | ByteBuffer buffer = ByteBuffer.allocate(1024);
105 | //��ȡ�������������ض�ȡ�����ֽ���
106 | int readBytes = sc.read(buffer);
107 | //��ȡ���ֽڣ����ֽڽ��б����
108 | if(readBytes>0){
109 | //����������ǰ��limit����Ϊposition=0�����ں����Ի������Ķ�ȡ����
110 | buffer.flip();
111 | //���ݻ������ɶ��ֽ��������ֽ�����
112 | byte[] bytes = new byte[buffer.remaining()];
113 | //���������ɶ��ֽ����鸴�Ƶ��½���������
114 | buffer.get(bytes);
115 | String expression = new String(bytes,"UTF-8");
116 | System.out.println("�������յ���Ϣ��" + expression);
117 | //��������
118 | String result = null;
119 | try{
120 | result = Calculator.Instance.cal(expression).toString();
121 | }catch(Exception e){
122 | result = "�������" + e.getMessage();
123 | }
124 | //����Ӧ����Ϣ
125 | doWrite(sc,result);
126 | }
127 | //û�ж�ȡ���ֽ� ����
128 | // else if(readBytes==0);
129 | //��·�Ѿ��رգ��ͷ���Դ
130 | else if(readBytes<0){
131 | key.cancel();
132 | sc.close();
133 | }
134 | }
135 | }
136 | }
137 | //�첽����Ӧ����Ϣ
138 | private void doWrite(SocketChannel channel,String response) throws IOException{
139 | //����Ϣ����Ϊ�ֽ�����
140 | byte[] bytes = response.getBytes();
141 | //����������������ByteBuffer
142 | ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
143 | //���ֽ����鸴�Ƶ�������
144 | writeBuffer.put(bytes);
145 | //flip����
146 | writeBuffer.flip();
147 | //���ͻ��������ֽ�����
148 | channel.write(writeBuffer);
149 | //****�˴���������д������Ĵ���
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/src/com/anxpp/io/calculator/nio/Test.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anxpp/Java-IO/7befe0aad46f6ed03e994214be88d74c1b99a669/src/com/anxpp/io/calculator/nio/Test.java
--------------------------------------------------------------------------------
/src/com/anxpp/io/utils/Calculator.java:
--------------------------------------------------------------------------------
1 | package com.anxpp.io.utils;
2 | import javax.script.ScriptEngine;
3 | import javax.script.ScriptEngineManager;
4 | import javax.script.ScriptException;
5 | public enum Calculator {
6 | Instance;
7 | private final static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
8 | public Object cal(String expression) throws ScriptException{
9 | return jse.eval(expression);
10 | }
11 | }
--------------------------------------------------------------------------------