Skip to content

Asynchronous socket, http(s) (client+server) and websocket library for android. Based on nio, not threads.

License

Notifications You must be signed in to change notification settings

koush/AndroidAsync

Repository files navigation

AndroidAsync

AndroidAsync is a low level network protocol library. If you are looking for an easy to use, higher level, Android aware, http request library, check out Ion (it is built on top of AndroidAsync). The typical Android app developer would probably be more interested in Ion.

But if you're looking for a raw Socket, HTTP(s) client/server, and WebSocket library for Android, AndroidAsync is it.

Features

  • Based on NIO. Single threaded and callback driven.
  • All operations return a Future that can be cancelled
  • Socket client + socket server
  • HTTP client + server
  • WebSocket client + server

Download

Download the latest JAR or grab via Maven:

<dependency> <groupId>com.koushikdutta.async</groupId> <artifactId>androidasync</artifactId> <version>(insert latest version)</version> </dependency>

Gradle:

dependencies{compile 'com.koushikdutta.async:androidasync:2.+' }

Download a url to a String

// url is the URL to download.AsyncHttpClient.getDefaultInstance().getString(url, newAsyncHttpClient.StringCallback(){// Callback is invoked with any exceptions/errors, and the result, if available.@OverridepublicvoidonCompleted(Exceptione, AsyncHttpResponseresponse, Stringresult){if (e != null){e.printStackTrace(); return} System.out.println("I got a string: " + result)} });

Download JSON from a url

// url is the URL to download.AsyncHttpClient.getDefaultInstance().getJSONObject(url, newAsyncHttpClient.JSONObjectCallback(){// Callback is invoked with any exceptions/errors, and the result, if available.@OverridepublicvoidonCompleted(Exceptione, AsyncHttpResponseresponse, JSONObjectresult){if (e != null){e.printStackTrace(); return} System.out.println("I got a JSONObject: " + result)} });

Or for JSONArrays...

// url is the URL to download.AsyncHttpClient.getDefaultInstance().getJSONArray(url, newAsyncHttpClient.JSONArrayCallback(){// Callback is invoked with any exceptions/errors, and the result, if available.@OverridepublicvoidonCompleted(Exceptione, AsyncHttpResponseresponse, JSONArrayresult){if (e != null){e.printStackTrace(); return} System.out.println("I got a JSONArray: " + result)} });

Download a url to a file

AsyncHttpClient.getDefaultInstance().getFile(url, filename, newAsyncHttpClient.FileCallback(){@OverridepublicvoidonCompleted(Exceptione, AsyncHttpResponseresponse, Fileresult){if (e != null){e.printStackTrace(); return} System.out.println("my file is available at: " + result.getAbsolutePath())} });

Caching is supported too

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

Need to do multipart/form-data uploads? That works too.

AsyncHttpPostpost = newAsyncHttpPost("http://myservercom/postform.html"); MultipartFormDataBodybody = newMultipartFormDataBody(); body.addFilePart("my-file", newFile("/path/to/file.txt"); body.addStringPart("foo", "bar"); post.setBody(body); AsyncHttpClient.getDefaultInstance().executeString(post, newAsyncHttpClient.StringCallback(){@OverridepublicvoidonCompleted(Exceptionex, AsyncHttpResponsesource, Stringresult){if (ex != null){ex.printStackTrace(); return} System.out.println("Server says: " + result)} });

Can also create web sockets:

AsyncHttpClient.getDefaultInstance().websocket(get, "my-protocol", newWebSocketConnectCallback(){@OverridepublicvoidonCompleted(Exceptionex, WebSocketwebSocket){if (ex != null){ex.printStackTrace(); return} webSocket.send("a string"); webSocket.send(newbyte[10]); webSocket.setStringCallback(newStringCallback(){publicvoidonStringAvailable(Strings){System.out.println("I got a string: " + s)} }); webSocket.setDataCallback(newDataCallback(){publicvoidonDataAvailable(DataEmitteremitter, ByteBufferListbyteBufferList){System.out.println("I got some bytes!"); // note that this data has been readbyteBufferList.recycle()} })} });

AndroidAsync also let's you create simple HTTP servers:

AsyncHttpServerserver = newAsyncHttpServer(); List<WebSocket> _sockets = newArrayList<WebSocket>(); server.get("/", newHttpServerRequestCallback(){@OverridepublicvoidonRequest(AsyncHttpServerRequestrequest, AsyncHttpServerResponseresponse){response.send("Hello!!!")} }); // listen on port 5000server.listen(5000); // browsing http://localhost:5000 will return Hello!!!

And WebSocket Servers:

AsyncHttpServerhttpServer = newAsyncHttpServer(); httpServer.listen(AsyncServer.getDefault(), port); httpServer.websocket("/live", newAsyncHttpServer.WebSocketRequestCallback(){@OverridepublicvoidonConnected(finalWebSocketwebSocket, AsyncHttpServerRequestrequest){_sockets.add(webSocket); //Use this to clean up any references to your websocketwebSocket.setClosedCallback(newCompletedCallback(){@OverridepublicvoidonCompleted(Exceptionex){try{if (ex != null) Log.e("WebSocket", "An error occurred", ex)} finally{_sockets.remove(webSocket)} } }); webSocket.setStringCallback(newStringCallback(){@OverridepublicvoidonStringAvailable(Strings){if ("Hello Server".equals(s)) webSocket.send("Welcome Client!")} })} }); //..Sometime later, broadcast!for (WebSocketsocket : _sockets) socket.send("Fireball!");

Futures

All the API calls return Futures.

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

Futures can also have callbacks...

Future<String> string = client.getString("http://foo.com/hello.txt"); string.setCallback(newFutureCallback<String>(){@OverridepublicvoidonCompleted(Exceptione, Stringresult){System.out.println(result)} });

For brevity...

client.getString("http://foo.com/hello.txt") .setCallback(newFutureCallback<String>(){@OverridepublicvoidonCompleted(Exceptione, Stringresult){System.out.println(result)} });

About

Asynchronous socket, http(s) (client+server) and websocket library for android. Based on nio, not threads.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

 

Packages

 
 
 

Languages