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)下载一个字符串

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

(2)下载一个Json

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

(3)下载一个文件

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

(4)支持缓存

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

(5)创建一个Socket

 AsyncHttpClient.getDefaultInstance().websocket(get, "my-protocol", new WebSocketConnectCallback() {
@Override
public void onCompleted(Exception ex, WebSocket webSocket) {
if (ex != null) {
ex.printStackTrace();
return;
}
webSocket.send("a string");
webSocket.send(new byte[10]);
webSocket.setStringCallback(new StringCallback() {
public void onStringAvailable(String s) {
System.out.println("I got a string: " + s);
}
});
webSocket.setDataCallback(new DataCallback() {
public void onDataAvailable(ByteBufferList byteBufferList) {
System.out.println("I got some bytes!");
// note that this data has been read
byteBufferList.recycle();
}
});
}
});

(6)支持socket io

 SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), "http://192.168.1.2:3000", new ConnectCallback() {
@Override
public void onConnectCompleted(Exception ex, SocketIOClient client) {
if (ex != null) {
ex.printStackTrace();
return;
}
client.setStringCallback(new StringCallback() {
@Override
public void onString(String string) {
System.out.println(string);
}
});
client.on("someEvent", new EventCallback() {
@Override
public void onEvent(JSONArray argument, Acknowledge acknowledge) {
System.out.println("args: " + arguments.toString());
}
});
client.setJSONCallback(new JSONCallback() {
@Override
public void onJSON(JSONObject json) {
System.out.println("json: " + json.toString());
}
});
}
});

(7)提交表单

 AsyncHttpPost post = new AsyncHttpPost("http://myservercom/postform.html");
MultipartFormDataBody body = new MultipartFormDataBody();
body.addFilePart("my-file", new File("/path/to/file.txt");
body.addStringPart("foo", "bar");
post.setBody(body);
AsyncHttpClient.getDefaultInstance().execute(post, new StringCallback() {
@Override
public void onCompleted(Exception e, AsyncHttpResponse source, String result) {
if (e != null) {
ex.printStackTrace();
return;
}
System.out.println("Server says: " + result);
}
});

(8)创建一个http server

 AsyncHttpServer server = new AsyncHttpServer();
List<WebSocket> _sockets = new ArrayList<WebSocket>();
server.get("/", new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
response.send("Hello!!!");
}
});
// listen on port 5000
server.listen(5000);
// browsing http://localhost:5000 will return Hello!!!

接着,创建一个websocket  server

 server.websocket("/live", new WebSocketRequestCallback() {
@Override
public void onConnected(final WebSocket webSocket, AsyncHttpServerRequest request) {
_sockets.add(webSocket);
//Use this to clean up any references to your websocket
websocket.setClosedCallback(new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
try {
if (ex != null)
Log.e("WebSocket", "Error");
} finally {
_sockets.remove(webSocket);
}
}
});
webSocket.setStringCallback(new StringCallback() {
@Override
public void onStringAvailable(String s) {
if ("Hello Server".equals(s))
webSocket.send("Welcome Client!");
}
});
}
});
//..Sometime later, broadcast!
for (WebSocket socket : _sockets)
socket.send("Fireball!");

(9)支持Future

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

5. AndroidAsync的下载

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

上一篇:php_os 检查php运行环境


下一篇:MySQL中concat函数