分享

AndroidAsync :一个基于nio的异步socket ,http(客户端服务器端),websocket,socket.io库

 gljin_cn 2014-10-05

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

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

特性

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

下载

1
2
3
4
5
<dependency>
    <groupId>com.koushikdutta.async</groupId>
    <artifactId>androidasync</artifactId>
    <version>(insert latest version)</version>
</dependency>

 

使用

下载一个字符串

1
2
3
4
5
6
7
8
9
10
11
12
// 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);
    }
});

下载一个JSON

1
2
3
4
5
6
7
8
9
10
11
12
// 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);
    }
});

下载到一个文件

1
2
3
4
5
6
7
8
9
10
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());
    }
});

支持缓存

1
2
3
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);

创建一个socket

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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();
            }
        });
    }
});

支持socket io

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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());
            }
        });
    }
});

提交表单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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);
    }
});

创建一个http  server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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!");

支持Future

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

GitHub:https://github.com/koush/AndroidAsync

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多