1. 程式人生 > >AndroidAsync :基於nio的非同步通訊庫

AndroidAsync :基於nio的非同步通訊庫

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 客戶端

下載

<dependency>

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

    <artifactId>androidasync</artifactId>

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

</dependency>

使用

下載一個字串

// 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

// 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);

    }

});

下載到一個檔案

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());

    }

});

支援快取

// 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

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

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());

            }

        });

    }

});

提交表單

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

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!");

支援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();

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