Coder Social home page Coder Social logo

androidasync's Introduction

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, 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);
    }
});

Download JSON from a url

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

Or for JSONArrays...

// url is the URL to download.
AsyncHttpClient.getDefaultInstance().getJSONArray(url, new AsyncHttpClient.JSONArrayCallback() {
    // Callback is invoked with any exceptions/errors, and the result, if available.
    @Override
    public void onCompleted(Exception e, AsyncHttpResponse response, JSONArray result) {
        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, 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());
    }
});

Caching is supported too

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

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

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().executeString(post, new AsyncHttpClient.StringCallback(){
        @Override
        public void onCompleted(Exception ex, AsyncHttpResponse source, String result) {
            if (ex != null) {
                ex.printStackTrace();
                return;
            }
            System.out.println("Server says: " + result);
        }
    });

Can also create web sockets:

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(DataEmitter emitter, ByteBufferList byteBufferList) {
                System.out.println("I got some bytes!");
                // note that this data has been read
                byteBufferList.recycle();
            }
        });
    }
});

AndroidAsync also let's you create simple HTTP servers:

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

And WebSocket Servers:

AsyncHttpServer httpServer = new AsyncHttpServer();

httpServer.listen(AsyncServer.getDefault(), port);

httpServer.websocket("/live", new AsyncHttpServer.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", "An error occurred", ex);
                } 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!");

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!
String value = string.get();

Futures can also have callbacks...

Future<String> string = client.getString("http://foo.com/hello.txt");
string.setCallback(new FutureCallback<String>() {
    @Override
    public void onCompleted(Exception e, String result) {
        System.out.println(result);
    }
});

For brevity...

client.getString("http://foo.com/hello.txt")
.setCallback(new FutureCallback<String>() {
    @Override
    public void onCompleted(Exception e, String result) {
        System.out.println(result);
    }
});

androidasync's People

Contributors

andhie avatar dsnatochy avatar elevenfive avatar ey3ball avatar gdaniels avatar glennporter-examtime avatar gongman11 avatar ilyagulya avatar justinwh avatar koush avatar mengyxinx avatar mkonecny avatar mkoslacz avatar mustafa01ali avatar nickaknudson avatar nsk-mironov avatar nutsiepully avatar pappz avatar paulpdaniels avatar renniepet avatar robux4 avatar s-arash avatar sst8696 avatar stuckless avatar swordsman-inaction avatar urmilparikh avatar vanwinkeljan avatar vcube-yunarta avatar vshivam avatar yuralaguta avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

androidasync's Issues

Socket.io namespacing support

Does this android socket.io client support socket.io namespacing? I've tried to use https://github.com/koush/android-websockets but it doesn't support namespacing. And as I see SocketIOClient class doesn't change too much. So is there any way to utilize namespaces like: "ws://localhost:3000/namespace1" or to set namespace on send?

WebSocket's setClosedCallback doesn't work

First, I'd like to thank you for this amazing lib, it's impressive! I'm using it to develop a WebSocket and Socket.io plugin for Game Closure.

I tried to use setClosedCallback and setEndCallback to handle onclose event, but these callbacks seem to be never called.

AsyncHttpClient.getDefaultInstance().websocket(url, protocol, new WebSocketConnectCallback() {
    @Override
    public void onCompleted(Exception ex, WebSocket websocket) {
        // onopen

        websocket.setStringCallback(new StringCallback() {
            public void onStringAvailable(String data) {
                // onmessage
            }
        });

        websocket.setClosedCallback(new CompletedCallback() {
            public void onCompleted(Exception ex) {
                // onclose
            }
        });

        websocket.setEndCallback(new CompletedCallback() {
            public void onCompleted(Exception ex) {
                // ???
            }
        });
    }
});

I have some questions about that:

  • Do I have a problem in my code or is there a bug?
  • What is the endCallback supposed to do?
  • During the closing operation, the websocket is supposed to continue to receive messages, but with this implementation, it seems to stop receiving messages just after the close statement. Is it a bug?
  • Is it possible to have the standard information that should be available with onclose event? (wasClean, code, reason)

Server Name Indication (SNI)

is there any way to add support for SNI?
right now, AsyncSSLSocketWrapper.handleResult is checking the host with a certificate. but it doesn't work if the server is using SNI.

TIA!!

Content-length - show stopper

In case the content length is bigger then 8192 b ~ (8K)
The post body content is not complete
So if i am sending a "big" json string , I am getting only part of the string

This is a blocking , show stopper issue

Websocket failed: One or more reserved bits are on

I am running the server on android and trying to connect to it from macbook on same network.

Getting the following error on chrome and firefox:
WebSocket connection to 'ws://192.168.0.102:8888/echo' failed: One or more reserved bits are on: reserved1 = 1, reserved2 = 0, reserved3 = 0

Firefox:
[21:25:49.381] The connection to ws://192.168.0.102:8888/echo was interrupted while the page was loading. @ http://192.168.0.102:8888/:7

Server code

    mServer = new AsyncHttpServer();
    mServer.get("/", new HttpServerRequestCallback() {
      @Override
      public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        response.send(readStream(getResources().openRawResource(R.raw.index)));
      }
    });
    mServer.websocket("/echo", new WebSocketRequestCallback() {

      @Override
      public void onConnected(WebSocket webSocket, RequestHeaders headers) {
        webSocket.setStringCallback(new StringCallback() {

          @Override
          public void onStringAvailable(String s) {
            Log.e("Socket", "msg : " + s);
          }
        });
      }
    });

    mServer.listen(8888);

index.html

<html>
<head>
<title>Web Socket test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function initws() {
    var connection = new WebSocket('ws://192.168.0.102:8888/echo', "chat");

    // When the connection is open, send some data to the server
    connection.onopen = function () {
        console.log('connected'); // Send the message 'Ping' to the server
    };

    // Log errors
    connection.onerror = function (error) {
      console.log('WebSocket Error', error);
    };

    // Log messages from the server
    connection.onmessage = function (e) {
      console.log("Message", e);
    };
}
</script>
</head>
<body>
<h1>Web Socket test</h1>
<button onclick="initws()">Connect</button>

Update:
Same error on chrome on android itself, so it should not be a firewall issue.
Also the error happens just after onopen as I am getting the 'connected' message. And if I send some message back from index.html in onopen, it is received by the server

In AsyncHttpServer, attempting to get the request user-agent results in null

Attempting to read the user-agent in the onRequest callback of AsyncHttpServer results in null.

    mServer = new AsyncHttpServer();
    mServer.get("/", new HttpServerRequestCallback() {

        @Override
        public void onRequest(AsyncHttpServerRequest request,
                AsyncHttpServerResponse response) {
            String userAgent = request.getHeaders().getUserAgent();
            response.send("Hello World!");
        }
    });

However, using the RawHeaders works fine:

userAgent = request.getHeaders().getHeaders().get("User-Agent");

client.emit( ) parameters

Hi,
I'm trying to do the following Socket.IO JavaScript code with the help of your library:

emit('subscribe', { 'channel' : 'test' });

I've tried doing this on Android using a JSONObject:

JSONObject args = new JSONObject():
args.put("channel", "test");
JSONObject message = new JSONObject();
message.put("name", "subscribe");
message.put("args", args);
client.emit(message, new Acknowlegde() {...})

I also tried using

client.of("test", callback)

But none of these worked. How am I supposed to add arguments to an emit call, like in JavaScript? I am trying to join a room/channel called test.

ASSERT/NetworkStats(93): problem reading network stats

I'm pretty sure this is not an issue with the program, but with my usage of it ...

07-20 00:44:50.183: ASSERT/NetworkStats(93): problem reading network stats
java.lang.IllegalStateException: problem parsing line: null
at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:313)
at com.android.server.NetworkManagementService.getNetworkStatsUidDetail(NetworkManagementService.java:1271)
at com.android.server.net.NetworkStatsService.performPollLocked(NetworkStatsService.java:810)
at com.android.server.net.NetworkStatsService.updateIfacesLocked(NetworkStatsService.java:721)
at com.android.server.net.NetworkStatsService.updateIfaces(NetworkStatsService.java:699)
at com.android.server.net.NetworkStatsService.access$000(NetworkStatsService.java:128)
at com.android.server.net.NetworkStatsService$1.onReceive(NetworkStatsService.java:589)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.os.HandlerThread.run(HandlerThread.java:60)
Caused by: java.io.FileNotFoundException: /proc/net/xt_qtaguid/stats: open failed: ENOENT (No such file or directory)
at libcore.io.IoBridge.open(IoBridge.java:406)
at java.io.FileInputStream.(FileInputStream.java:78)
at java.io.FileReader.(FileReader.java:42)
at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:272)
... 11 more
Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
at libcore.io.Posix.open(Native Method)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:98)
at libcore.io.IoBridge.open(IoBridge.java:390)
... 14 more

I have not (yet) given my app permission to read or write external storage - this is presumably the cause? But is it inteded that the logged exception "java.lang.IllegalStateException: problem parsing line: null" should occur?

On a completely different note, I don't suppose there are any sample apps available that demonstrate how to connect and send and receive simple tcp/ip packets? No http, no json, no ssl ...

Socket.io XHR support

Hi,

I'm not sure what I'm doing wrong but I'm getting the following error when trying to connect to my socket.io server:

System.err  W  java.lang.NumberFormatException: Invalid int: "//fonts.googleapis.com/css?family=Open+Sans"
System.err  W   at java.lang.Integer.invalidInt(Integer.java:138)
System.err  W   at java.lang.Integer.parse(Integer.java:375)
System.err  W   at java.lang.Integer.parseInt(Integer.java:366)
System.err  W   at java.lang.Integer.parseInt(Integer.java:332)
System.err  W   at com.koushikdutta.async.http.socketio.SocketIOConnection$1.onCompleted(SocketIOConnection.java:112)
System.err  W   at com.koushikdutta.async.http.socketio.SocketIOConnection$1.onCompleted(SocketIOConnection.java:100)
System.err  W   at com.koushikdutta.async.http.AsyncHttpClient.invokeWithAffinity(AsyncHttpClient.java:443)
System.err  W   at com.koushikdutta.async.http.AsyncHttpClient.access$500(AsyncHttpClient.java:40)
System.err  W   at com.koushikdutta.async.http.AsyncHttpClient$4.run(AsyncHttpClient.java:450)
System.err  W   at com.koushikdutta.async.AsyncServer.lockAndRunQueue(AsyncServer.java:749)
System.err  W   at com.koushikdutta.async.AsyncServer.runLoop(AsyncServer.java:760)
System.err  W   at com.koushikdutta.async.AsyncServer.run(AsyncServer.java:664)
System.err  W   at com.koushikdutta.async.AsyncServer.access$700(AsyncServer.java:34)
System.err  W   at com.koushikdutta.async.AsyncServer$14.run(AsyncServer.java:612)

I'm using a very simple socket.io server (the one from the socket.io site):

var io = require('socket.io').listen(8080);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

It works fine when connecting from a webbrowser.

And this is the Android code I'm using (pretty much taken from the readme):

SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), wsuri, new ConnectCallback() {
    @Override
    public void onConnectCompleted(Exception ex, SocketIOClient client) {
        if (ex != null) {
            Log.i(TAG, "ex is not null!");
            ex.printStackTrace();
            return;
        }
        client.setStringCallback(new StringCallback() {
            @Override
            public void onString(String string, Acknowledge acknowledge) {
                System.out.println(string);
            }
        });

        client.setJSONCallback(new JSONCallback() {
            @Override
            public void onJSON(JSONObject json, Acknowledge acknowledge) {
                System.out.println("json: " + json.toString());
            }
        });
    }
});

I'm not sure if I'm doing something wrong here. I tried it yesterday with version 1.1.3 and today with the new 1.1.4.

Thanks!

Socket.io client timeout

Hi,

I am currently using the AndroidAsync library to developing Android app. I have a node.js socket.io server which has heartbeat timeout set at 280 secs, close timeout 120 secs, heartbeat interval 115 secs. However, every 60 secs my socket.io client will disconnect from the server. May I know if I should change any value in the library to accommodate this?

Thanks.

Issue when the Content-length and Transfer-encoding headers are not present

In this case, androidasync drops the connection after receiving the first packets.

I was using (ion ๐Ÿ‘ ) downloading pictures from cloudfront and when a cache miss happens, cloudfront goes to the origin server which served chunked data, and serves it back without transfer-encoding or content-length headers. We fixed the issue server-side by setting content-length on the server.

Typically, it downloads 15Kb of a 90Kb picture and then drops the connection. (I saw this with wireshark)
Ion then tries to decode the partial data but skia fails as it cant decode partial pictures.

From this doc, I assume it should wait for the server to close the connection.

UrlImageViewHelper and Picasso are not affected.

I tried to pinpoint the faulty code and found it might be around line 178 in AsyncHttpResponseImpl but I am not sure.

Crashes when cancelling futures

I am having a problem when cancelling futures that I obtained using the format,

Future future = AsyncHttpClient.getDefaultInstance().get(getUrl, new AsyncHttpClient.StringCallback() {...} });

If the server does not respond, the user can click back twice to cancel the network operation. More often than not, this causes the following crash:

Capture1

And if I surround the above with a null check, I get this crash instead:

Capture

I am not sure why the callback immediately becomes null when issuing a cancel but that can be fixed fairly easily; however, I'm stumped as to how to prevent the crash at the assert without removing the entire call. I guess I'm curious if I am doing something wrong in the first place. I'm assuming the reason for returning a future was to give the ability to cancel, but is there something else I should do to prevent the crash like some cleanup of the prior operation?

Post Handling

Can you please add post support to the AsyncHttpServer?

Socket.IO callback function support

Hi,

I have an app using socket.io(nodejs) and most of my socket.on methods(server side) is using the callback function "fn" to retrieve data to the client. There's a way to use those same callback function "fn" to retrieve data to my AndroidAsync client?

Thank you!

ps: sorry about my english.

SSL Issues: bad_record_mac

about:
W/System.err: javax.net.ssl.SSLException: Fatal alert received bad_record_mac
W/System.err: at org.apache.harmony.xnet.provider.jsse.SSLEngineImpl.unwrap(SSLEngineImpl.java:485)
W/System.err: at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:383)
W/System.err: at com.koushikdutta.async.AsyncSSLSocketWrapper$1.onDataAvailable(AsyncSSLSocketWrapper.java:91)
W/System.err: at com.koushikdutta.async.BufferedDataEmitter.onDataAvailable(BufferedDataEmitter.java:33)
W/System.err: at com.koushikdutta.async.BufferedDataEmitter.onDataAvailable(BufferedDataEmitter.java:61)
W/System.err: at com.koushikdutta.async.Util.emitAllData(Util.java:20)
W/System.err: at com.koushikdutta.async.AsyncNetworkSocket.onReadable(AsyncNetworkSocket.java:170)
W/System.err: at com.koushikdutta.async.AsyncServer.runLoop(AsyncServer.java:805)
W/System.err: at com.koushikdutta.async.AsyncServer.run(AsyncServer.java:664)
W/System.err: at com.koushikdutta.async.AsyncServer.access$700(AsyncServer.java:34)
W/System.err: at com.koushikdutta.async.AsyncServer$14.run(AsyncServer.java:612)

you said that forcing SSLv3 could solve it. but how do I force it?
TIA

new error

Hi, sorry but I have another exception, this time, it uploads up to 100% and then:
it happens every time I try. the file is only 100KB. any idea what it could be? I know the server works, because there are other implementations/clients that can upload images.

                  W/System.err: javax.net.ssl.SSLException: Fatal alert received bad_record_mac
                  W/System.err: at org.apache.harmony.xnet.provider.jsse.SSLEngineImpl.unwrap(SSLEngineImpl.java:485)
                  W/System.err: at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:383)
                  W/System.err: at com.koushikdutta.async.AsyncSSLSocketWrapper$1.onDataAvailable(AsyncSSLSocketWrapper.java:91)
                  W/System.err: at com.koushikdutta.async.BufferedDataEmitter.onDataAvailable(BufferedDataEmitter.java:33)
                  W/System.err: at com.koushikdutta.async.BufferedDataEmitter.onDataAvailable(BufferedDataEmitter.java:61)
                  W/System.err: at com.koushikdutta.async.Util.emitAllData(Util.java:20)
                  W/System.err: at com.koushikdutta.async.AsyncNetworkSocket.onReadable(AsyncNetworkSocket.java:170)
                  W/System.err: at com.koushikdutta.async.AsyncServer.runLoop(AsyncServer.java:805)
                  W/System.err: at com.koushikdutta.async.AsyncServer.run(AsyncServer.java:664)
                  W/System.err: at com.koushikdutta.async.AsyncServer.access$700(AsyncServer.java:34)
                  W/System.err: at com.koushikdutta.async.AsyncServer$14.run(AsyncServer.java:612)

Thanks!

Socket.IO Query Support

According to Socket.IO HTTP requests:

User-defined query components are allowed. For example, "?t=1238141910&token=mytoken" is a valid query.

But I can't find such as setQuery or setParams in SocketIORequest class

SocketIO onEvent not triggered

When in socket.io i do socket.emit("myevent") without any argument the onEvent callback is not triggered.

p.s.: thank you for this amazing library, even if it's very young it's pretty stable and even if some features are missing the implemented ones work very well.

Can't stop SocketIO to try to connect

Sometimes it happens that there is a proxy that brakes websocket so I added a timer, if the app can't connect within 10 seconds then it gives up and shows an error.

But how can I tell SocketIOClient to stop connecting once I called SocketIOClient.connect() ?

Socket.io queries.

I am migrating my socket.io implementation from this https://github.com/Gottox/socket.io-java-client to AndroidAsync. I couldn't find the alternate for certain use-cases that i used in that library. Please help me with the following use-cases.
1.How to check whether socket.io is connected or not?
2.How to disconnect socket connection?
3.How to reconnect socket?

websocket xhr switch

Can socket switch from web-socket to xhr if web-socket does not work on certain situations?
Is there an option to switch to xhr and back according to the network conditions (WiFi,3G)?

WebSocket in IE10

WebSockets work in all browsers except IE10, this error in browser: "WebSocket Error: Incorrect HTTP response. Status code 404, Not Found" and this in app:

07-29 19:36:36.624: E/NIO(8764): Unhandled exception
07-29 19:36:36.624: E/NIO(8764): java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
07-29 19:36:36.624: E/NIO(8764):    at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java)
07-29 19:36:36.624: E/NIO(8764):    at libcore.io.IoBridge.recvfrom(IoBridge.java)
07-29 19:36:36.624: E/NIO(8764):    at java.nio.SocketChannelImpl.readImpl(SocketChannelImpl.java)
07-29 19:36:36.624: E/NIO(8764):    at java.nio.SocketChannelImpl.read(SocketChannelImpl.java)
07-29 19:36:36.624: E/NIO(8764):    at com.koushikdutta.async.SocketChannelWrapper.read(SocketChannelWrapper.java:24)
07-29 19:36:36.624: E/NIO(8764):    at com.koushikdutta.async.AsyncNetworkSocket.onReadable(AsyncNetworkSocket.java:151)
07-29 19:36:36.624: E/NIO(8764):    at com.koushikdutta.async.AsyncServer.runLoop(AsyncServer.java:803)
07-29 19:36:36.624: E/NIO(8764):    at com.koushikdutta.async.AsyncServer.run(AsyncServer.java:662)
07-29 19:36:36.624: E/NIO(8764):    at com.koushikdutta.async.AsyncServer.access$5(AsyncServer.java:651)
07-29 19:36:36.624: E/NIO(8764):    at com.koushikdutta.async.AsyncServer$14.run(AsyncServer.java:610)
07-29 19:36:36.624: E/NIO(8764): Caused by: libcore.io.ErrnoException: recvfrom failed: ECONNRESET (Connection reset by peer)
07-29 19:36:36.624: E/NIO(8764):    at libcore.io.Posix.recvfromBytes(Native Method)
07-29 19:36:36.624: E/NIO(8764):    at libcore.io.Posix.recvfrom(Posix.java)
07-29 19:36:36.624: E/NIO(8764):    at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java)
07-29 19:36:36.624: E/NIO(8764):    ... 9 more

Connecting via websockets

Is there a code sample to connect to a server via websockets? I'm trying to connect to a sockjs server but I keep receiving timeouts:

AsyncHttpClient.getDefaultInstance().websocket("ws://ddptesttp.meteor.com/websocket", null, new AsyncHttpClient.WebSocketConnectCallback() {
    @Override
    public void onCompleted(Exception ex, WebSocket webSocket) {
        if (ex != null) {
            System.out.println("I got an error");
            ex.printStackTrace();
                return;
            }

            webSocket.setStringCallback(new WebSocket.StringCallback() {
                public void onStringAvailable(String s) {
                    System.out.println("I got: " + s);
                }
            });
        }
});

Error in README - no constructor for AsyncHttpServer that takes a port as argument

The HTTP Server example in README says this:
AsyncHttpServer mServer = new AsyncHttpServer(5000);

However, there is no constructor for AsyncHttpServer that takes a port as constructor. The example should read:

AsyncHttpServer mServer = new AsyncHttpServer();
mServer.get("/", new HttpServerRequestCallback() {
    @Override
    public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        response.send("Hello!!!");
    }
});
mServer.listen(5000);

Socket.IO acknowledgement

Hi,

I am looking for acknowledgment function for the socket io client, there are some socket event callback in my project need to get acknowledgement. Is this available?

Thanks.

Exception

Hi again :)
I'm having this exception:

I'm uploading a file, it finish to upload and the file is uploaded ok. but the callback comes with an exception as a parameter.

any idea?
Thanks!

W/System.err( 2128): java.lang.NullPointerException
W/System.err( 2128): at ajo.onDataAvailable(SourceFile:239)
W/System.err( 2128): at com.koushikdutta.async.DataEmitterReader.a(SourceFile:23)
W/System.err( 2128): at com.koushikdutta.async.DataEmitterReader.onDataAvailable(SourceFile:38)
W/System.err( 2128): at com.koushikdutta.async.Util.emitAllData(SourceFile:20)
W/System.err( 2128): at com.koushikdutta.async.FilteredDataEmitter.onDataAvailable(SourceFile:50)
W/System.err( 2128): at com.koushikdutta.async.http.filter.ContentLengthFilter.onDataAvailable(SourceFile:31)
W/System.err( 2128): at com.koushikdutta.async.Util.emitAllData(SourceFile:20)
W/System.err( 2128): at aik.onDataAvailable(SourceFile:113)
W/System.err( 2128): at com.koushikdutta.async.BufferedDataEmitter.onDataAvailable(SourceFile:33)
W/System.err( 2128): at com.koushikdutta.async.BufferedDataEmitter.onDataAvailable(SourceFile:61)
W/System.err( 2128): at com.koushikdutta.async.Util.emitAllData(SourceFile:20)
W/System.err( 2128): at com.koushikdutta.async.AsyncNetworkSocket.b(SourceFile:170)
W/System.err( 2128): at com.koushikdutta.async.AsyncServer.c(SourceFile:805)
W/System.err( 2128): at com.koushikdutta.async.AsyncServer.b(SourceFile:664)
W/System.err( 2128): at com.koushikdutta.async.AsyncServer.a(SourceFile:34)
W/System.err( 2128): at air.run(SourceFile:612)
W/System.err( 2128): java.lang.NullPointerException
W/System.err( 2128): at com.koushikdutta.async.DataEmitterReader.a(SourceFile:23)
W/System.err( 2128): at com.koushikdutta.async.DataEmitterReader.onDataAvailable(SourceFile:38)
W/System.err( 2128): at com.koushikdutta.async.Util.emitAllData(SourceFile:20)
W/System.err( 2128): at com.koushikdutta.async.FilteredDataEmitter.onDataAvailable(SourceFile:50)
W/System.err( 2128): at com.koushikdutta.async.http.filter.ContentLengthFilter.onDataAvailable(SourceFile:31)
W/System.err( 2128): at com.koushikdutta.async.Util.emitAllData(SourceFile:20)
W/System.err( 2128): at aik.onDataAvailable(SourceFile:113)
W/System.err( 2128): at com.koushikdutta.async.BufferedDataEmitter.onDataAvailable(SourceFile:33)
W/System.err( 2128): at com.koushikdutta.async.BufferedDataEmitter.onDataAvailable(SourceFile:61)
W/System.err( 2128): at com.koushikdutta.async.Util.emitAllData(SourceFile:20)
W/System.err( 2128): at com.koushikdutta.async.AsyncNetworkSocket.b(SourceFile:170)
W/System.err( 2128): at com.koushikdutta.async.AsyncServer.c(SourceFile:805)
W/System.err( 2128): at com.koushikdutta.async.AsyncServer.b(SourceFile:664)
W/System.err( 2128): at com.koushikdutta.async.AsyncServer.a(SourceFile:34)

datagramchannel

Hi,is there any trouble if you using the android's DatagramChannel.receive()
to get some data?
I found that the receive() can not get any message from the remote peer,but the read(),method can,

Problem with slow data transfer? (High ping)

Hi,

I am trying to make real-time multiplayer android game using your socket.io library. Everything works fine but data transfer seems to be too slow (about 0.7 sec delay). Can u please suggest something to make this connection a bit faster. On server side I am using node.js (express) with socket.io on nodejitsu.

  1. I am establishing connection wtih this snippet:

try {

client = SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), "http://igrica.nodejitsu.com/", null).get();

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  1. Packing in JSONObject, JSONArray and emmiting on server

    final JSONObject obj = new JSONObject();
    final JSONArray arr = new JSONArray();

    try {
    obj.put("velx", x);
    obj.put("vely", y);
    } catch (JSONException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    }

            try {
                arr.put(0, obj);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
  2. Listening on response:

client.on("listening", new EventCallback(){

        @Override
        public void onEvent(JSONArray data, Acknowledge arg1) {
            // TODO Auto-generated method stub
            try {
                //Log.e(null, data.getJSONObject(0).getString("velx"));

                faceBody.setLinearVelocity(new Vector2(Float.parseFloat(data.getJSONObject(0).getString("velx"))*5,Float.parseFloat(data.getJSONObject(0).getString("vely"))*5));



            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 

        }});

Sorry for bad format and thanks in advance:).

I don't know if that is an issue but i think so... INFO/AsyncHttpSocket(3876)

i got a local socket.io server, that gave a response on connect with you lib.
but than i became

INFO/AsyncHttpSocket(3876): com.koushikdutta.async.http.AsyncSSLSocketMiddleware Not keeping non-owned socket: null

and than i send text to the socket for the android device and there is no response...

public void socketConnect(){
String socketUrl = "http://192.168.0.117:7788";
Log.d("Socket ", " try to connect "+ socketUrl +" " + UserData.getInstance().getToken());
SocketIOClient.SocketIORequest request = new SocketIOClient.SocketIORequest( socketUrl );
request.setHeader("token", UserData.getInstance().getToken());

    SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), request, new SocketIOClient.SocketIOConnectCallback() {
        @Override
        public void onConnectCompleted(Exception ex, SocketIOClient client) {
            if (ex != null) {
                Log.d("Socket", "no connection " + ex.getMessage());
                ex.printStackTrace();
                return;
            }

            Log.d("Socket", "maybe connected?");
            client.setStringCallback(new SocketIOClient.StringCallback() {
                @Override
                public void onString(String string) {
                    Log.d("Socket", "string... conn. lalalal");
                    System.out.println(string);
                }
            });

            client.setEventCallback(new EventCallback() {
                @Override
                public void onEvent(String event, org.json.JSONArray arguments) {
                    //To change body of implemented methods use File | Settings | File Templates.
                    Log.d("Socket", "Event");
                }
            });
            client.setJSONCallback(new SocketIOClient.JSONCallback() {
                @Override
                public void onJSON(org.json.JSONObject json) {
                    //To change body of implemented methods use File | Settings | File Templates.
                    Log.d("Socket", "JSON");
                }
            });

        }

    });
}

cancel() not working

Hi,

when I call cancel() on the Future I get from getFile(...), the download is not cancelled when the download is running already, only when it is called directly after the getFile() call:

AsyncHttpClient client = AsyncHttpClient.getDefaultInstance();
Future futureFile = client.getFile(url, path, callback);
futureFile.cancel(); -> works
SystemClock.sleep(1000);
futureFile.cancel(); -> does not work anymore (first cancel() is removed of course)

Regards,

Marc

Future get() only blocks for ~20 sec preventing longer network requests from completing

I am using futures that return a string as follows:

Future future = AsyncHttpClient.getDefaultInstance().getString(someUrl);
String result = future.get();

However, this throws an exception withing 20-30 seconds exactly, "java.util.concurrent.ExecutionException: java.util.concurrent.TimeoutException". I have even tried using the get(timeout, TimeUnit) method with the same result no matter the value for timeout. All the other requests to the same server that return more quickly all complete normally. At the very least, get() should block until specifically cancelled or the thread was interrupted and not throw a TimeoutException.

Streaming binary data to websocket server

I have created a websocket server with this library, but I can't seem to find any way to accept streaming data on a websocket connection.

Is there a way to do this with AndroidAsync?

Sec-WebSocket-Key should be base64 encoded instead of UUID string

The websocket client implementation sends the generated UUID as a string instead of base64 encoded

RFC 6455 - 4.1. Client Requirements

  1. The request MUST include a header field with the name
    |Sec-WebSocket-Key|. The value of this header field MUST be a
    nonce consisting of a randomly selected 16-byte value that has
    been base64-encoded (see Section 4 of [RFC4648]). The nonce
    MUST be selected randomly for each connection.

WebSocket server - receiving messages?

Apologies if this is a newbie misunderstanding, but is there currently no way to receive messages when hosting a WebSocket server?

I can't find any callback that fires for receiving WebSocket messages (on the server side) after the initial onConnected(). I tried using WebSocket.setStringCallback() but think that's intended for the client side.

configurable socket.io recconectDelay

Is it possible to set reconnectDelay manually?

In my case, let's say android lost connection. I want to bring back the connection ASAP.

Maybe there is another more appropriate solution to this problem ?

Callback event not triggered

Hi,
I'm using the code below for socket communication. My socket gets connected and disconnected succesfully but when i do socket.emit(String name, JsonArray args), no callback events are triggered. I don't understand what i'm doing wrong. Please help me.

 SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), req, new                              
 ConnectCallback()   {                  
  @Override
  public void onConnectCompleted(Exception ex, SocketIOClient client) {

 if (ex != null) {
        Log.i("SOCKET", "ex is not null!");
        ex.printStackTrace();
        return;
    }

client.setErrorCallback(new ErrorCallback() {

    @Override
    public void onError(String arg0) {

        Log.e("SOCKET", "Socket error: " + arg0);

    }
});
client.setDisconnectCallback(new DisconnectCallback() {

    @Override
    public void onDisconnect(Exception arg0) {

        Log.i("SOCKET", "Socket disconnected: " + arg0);

    }
});

client.on("String", new EventCallback() {

    @Override
    public void onEvent(JSONArray arg0, Acknowledge arg1) {
        Log.i("SOCKET", "Event call back");

    }
});
client.setJSONCallback(new JSONCallback() {
    @Override
    public void onJSON(JSONObject json, Acknowledge acknowledge) {
        Log.i("SOCKET", "Json call back");
    }
});

}
});

http request returns "" .(May be i use it wrong)

I use post method in this way:

String my_way() {
AsyncHttpPost httpPost = new AsyncHttpPost("URL");
httpPost.setBody(new StringBody("StringBody"));
Future f = AsyncHttpClient.getDefaultInstance().executeString(httpPost);
String s = f.get();
return s;
}

It returns what i want most of time. But if i call it to frequently, it results s = "".

for(int i=0;i<10;i++) {
system.out.println(my_way());
}

results:
"Right Message"
""
"Right Message"
""
"Right Message"
""
"Right Message"
""
"Right Message"
""

I am sure that the server side is ok, because another lib has pass this test.

It happens even i use it like this

for(int i=0;i<10;i++) {
thread.sleep(1000);
system.out.println(my_way());
}

JSONRequestBody missing method

Hi,

I just downloaded the latest version (commit 0a1bf13). and there JSONRequestBody is missing the get() method from DataParser. Is this work in progress? Which version can you recommend for usage?

Thx in advance,

Marc

WebRTC support

There is a native library but that seems to be overly complicated to use and target audio/video.
An abstract interface for data connections could be very useful for mobile game development

JsonObject- JsonArray problem

in case i am sending json request
the code in httpUtil :

if (JSONObjectBody.CONTENT_TYPE.equals(ct)) {
return new JSONObjectBody();
}

does not check if its a json object or array so in case its array like [{ "a":"b"} ]
request.getBody() will return null as it will not parse the JSONArray

unless i will change the code like

if (JSONObjectBody.CONTENT_TYPE.equals(ct)) {
return new JSONArrayBody ();
}

but now i wil get null value in case the request body is json object and not json array

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.