Java基础知识强化之网络编程笔记24:Android网络通信之 AndroidAsync(基于nio的异步通信库)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java基础知识强化之网络编程笔记24:Android网络通信之 AndroidAsync(基于nio的异步通信库)相关的知识,希望对你有一定的参考价值。

1. AndroidAsync  

  AndroidAsync 是一个基于nio的异步socket ,http(客户端服务器端),websocket,socket.io库,androidAsync 是一个底层的网络协议库,如果你想要一个容易使用,高级的,http请求库,请使用Ion(它是基于AndroidAsync 的),正常来说开发者更倾向于使用  Ion。

如果你需要一个未被封装的Android的raw Socket, HTTP client/server, WebSocket, and Socket.IO, AndroidAsync 正适合你。

 

2. AndroidAsync 的特性

  • 基于NIO,一个线程,回调驱动,高效
  •  所有的操作返回一个Future,而且可以取消
  • All operations return a Future that can be cancelled
  • Socket client + socket server
  • HTTP client + server
  • WebSocket client + server
  • Socket.IO 客户端

 

3. AndroidAsync 的下载

<dependency>

    <groupId>com.koushikdutta.async</groupId>

    <artifactId>androidasync</artifactId>

    <version>(insert latest version)</version>

</dependency>

 

 

4. AndroidAsync 的使用

(1)下载一个字符串

 1 // url is the URL to download.
 2 AsyncHttpClient.getDefaultInstance().getString(url, new AsyncHttpClient.StringCallback() {
 3     // Callback is invoked with any exceptions/errors, and the result, if available.
 4     @Override
 5     public void onCompleted(Exception e, AsyncHttpResponse response, String result) {
 6         if (e != null) {
 7             e.printStackTrace();
 8             return;
 9         }
10         System.out.println("I got a string: " + result);
11     }
12 });

 

(2)下载一个Json

 1 // url is the URL to download.
 2 AsyncHttpClient.getDefaultInstance().getJSONObject(url, new AsyncHttpClient.JSONObjectCallback() {
 3     // Callback is invoked with any exceptions/errors, and the result, if available.
 4     @Override
 5     public void onCompleted(Exception e, AsyncHttpResponse response, JSONObject result) {
 6         if (e != null) {
 7             e.printStackTrace();
 8             return;
 9         }
10         System.out.println("I got a JSONObject: " + result);
11     }
12 });

 

(3)下载一个文件

 1 AsyncHttpClient.getDefaultInstance().getFile(url, filename, new AsyncHttpClient.FileCallback() {
 2     @Override
 3     public void onCompleted(Exception e, AsyncHttpResponse response, File result) {
 4         if (e != null) {
 5             e.printStackTrace();
 6             return;
 7         }
 8         System.out.println("my file is available at: " + result.getAbsolutePath());
 9     }
10 });

 

(4)支持缓存

1 // arguments are the http client, the directory to store cache files, and the size of the cache in bytes
2 ResponseCacheMiddleware.addCache(AsyncHttpClient.getDefaultInstance(),
3                                   getFileStreamPath("asynccache"),
4                                   1024 * 1024 * 10);

 

(5)创建一个Socket

 1 AsyncHttpClient.getDefaultInstance().websocket(get, "my-protocol", new WebSocketConnectCallback() {
 2     @Override
 3     public void onCompleted(Exception ex, WebSocket webSocket) {
 4         if (ex != null) {
 5             ex.printStackTrace();
 6             return;
 7         }
 8         webSocket.send("a string");
 9         webSocket.send(new byte[10]);
10         webSocket.setStringCallback(new StringCallback() {
11             public void onStringAvailable(String s) {
12                 System.out.println("I got a string: " + s);
13             }
14         });
15         webSocket.setDataCallback(new DataCallback() {
16             public void onDataAvailable(ByteBufferList byteBufferList) {
17                 System.out.println("I got some bytes!");
18                 // note that this data has been read
19                 byteBufferList.recycle();
20             }
21         });
22     }
23 });

 

(6)支持socket io

 1 SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), "http://192.168.1.2:3000", new ConnectCallback() {
 2     @Override
 3     public void onConnectCompleted(Exception ex, SocketIOClient client) {
 4         if (ex != null) {
 5             ex.printStackTrace();
 6             return;
 7         }
 8         client.setStringCallback(new StringCallback() {
 9             @Override
10             public void onString(String string) {
11                 System.out.println(string);
12             }
13         });
14         client.on("someEvent", new EventCallback() {
15             @Override
16             public void onEvent(JSONArray argument, Acknowledge acknowledge) {
17                 System.out.println("args: " + arguments.toString());
18             }
19         });
20         client.setJSONCallback(new JSONCallback() {
21             @Override
22             public void onJSON(JSONObject json) {
23                 System.out.println("json: " + json.toString());
24             }
25         });
26     }
27 });

 

(7)提交表单

 1 AsyncHttpPost post = new AsyncHttpPost("http://myservercom/postform.html");
 2 MultipartFormDataBody body = new MultipartFormDataBody();
 3 body.addFilePart("my-file", new File("/path/to/file.txt");
 4 body.addStringPart("foo", "bar");
 5 post.setBody(body);
 6 AsyncHttpClient.getDefaultInstance().execute(post, new StringCallback() {
 7     @Override
 8     public void onCompleted(Exception e, AsyncHttpResponse source, String result) {
 9         if (e != null) {
10             ex.printStackTrace();
11             return;
12         }
13         System.out.println("Server says: " + result);
14     }
15 });



(8)创建一个http server

 1 AsyncHttpServer server = new AsyncHttpServer();
 2 List<WebSocket> _sockets = new ArrayList<WebSocket>();
 3 server.get("/", new HttpServerRequestCallback() {
 4     @Override
 5     public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
 6         response.send("Hello!!!");
 7     }
 8 });
 9 // listen on port 5000
10 server.listen(5000);
11 // browsing http://localhost:5000 will return Hello!!!

接着,创建一个websocket  server

 

 1 server.websocket("/live", new WebSocketRequestCallback() {
 2     @Override
 3     public void onConnected(final WebSocket webSocket, AsyncHttpServerRequest request) {
 4         _sockets.add(webSocket);
 5         //Use this to clean up any references to your websocket
 6         websocket.setClosedCallback(new CompletedCallback() {
 7             @Override
 8             public void onCompleted(Exception ex) {
 9                 try {
10                     if (ex != null)
11                         Log.e("WebSocket", "Error");
12                 } finally {
13                     _sockets.remove(webSocket);
14                 }
15             }
16         });
17         webSocket.setStringCallback(new StringCallback() {
18             @Override
19             public void onStringAvailable(String s) {
20                 if ("Hello Server".equals(s))
21                     webSocket.send("Welcome Client!");
22             }
23         });
24     }
25 });
26 //..Sometime later, broadcast!
27 for (WebSocket socket : _sockets)
28     socket.send("Fireball!");

 

(9)支持Future

1 Future<String> string = client.getString("http://foo.com/hello.txt");
2 // this will block, and may also throw if there was an error!
3 String value = string.get();

 

 

5. AndroidAsync的下载

开源地址:https://github.com/koush/AndroidAsync

 

以上是关于Java基础知识强化之网络编程笔记24:Android网络通信之 AndroidAsync(基于nio的异步通信库)的主要内容,如果未能解决你的问题,请参考以下文章

Java基础知识强化之IO流笔记79:NIO之 SocketChannel

Java基础知识强化之IO流笔记80:NIO之 ServerSocketChannel

Java基础知识强化之IO流笔记76:NIO之 Channel(通道)之间的数据传输

Java:Effective java学习笔记之 用私有构造器或者枚举类型强化SIngleton属性

Java:Effective java学习笔记之 通过私有构造器强化不可实例化的能力

强化学习笔记之动态规划法