Code Monkey home page Code Monkey logo

socket.io-client-java's Introduction

Socket.IO-client Java

Build Status

This is the Socket.IO Client Library for Java, which is simply ported from the JavaScript client.

See also:

Table of content

Compatibility

Client version Socket.IO server
0.9.x 1.x
1.x 2.x
2.x 3.x / 4.x

Documentation

The documentation can be found here.

The source of this documentation is in the src/site/ directory of the repository. Pull requests are welcome!

License

MIT

socket.io-client-java's People

Contributors

alfioemanuelefresta avatar arghaffari avatar civanyp avatar darrachequesne avatar farmerswrap avatar hellpf avatar ifedapoolarewaju avatar isoteriksoftware avatar junbong avatar kushtrimpacaj avatar kylestev avatar lu-zero avatar naartjie avatar niqo01 avatar nkzawa avatar pamepros avatar sdaurea avatar shobhitpuri avatar twofingerrightclick avatar yujiosaka avatar zhxnlai 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

socket.io-client-java's Issues

Cant reconnect to a socket connected before

Hi, I disconnect to a socket, to change to a different namespace and when a I want to get back to a namespace connected before the EVENT_CONNECT never fires, due to the socket never connect.

This is the flow:
Connect a socket: socket = IO.socket("http://sting.jit.si/urucas-sting"); // connected: yes
Disconnect this socket: socket.disconnect(); // disconnected: yes
Connect another: socket = IO.socket("http://sting.jit.si/urucas-appium"); // connected: yes
Disconnect this socket: socket.disconnect(); // disconnected: yes
Connect to the first: socket = IO.socket("http://sting.jit.si/urucas-sting"); // connected: no :(

Is this a bug ? Or I shouldn't disconnect from a socket ?
I also tried with socket.close(), but it never reconnects.

What I did to make it work is to save the socket instances in a hashmap, but I think it would be better to use .disconnect

Error in Java Project - imported JAR

Hi,
I imported jar files (socketio and engineio) from Maven to eclipse project lib but it gives no class def found error. i checked both of them on build path / export.

http://mvnrepository.com/artifact/com.github.nkzawa/socket.io-client/0.1.3
http://mvnrepository.com/artifact/com.github.nkzawa/engine.io-client/0.2.3

Exception in thread "main" java.lang.NoClassDefFoundError: org/json/JSONException
at com.github.nkzawa.socketio.client.Manager.(Manager.java:143)
at com.github.nkzawa.socketio.client.IO.socket(IO.java:73)
at com.github.nkzawa.socketio.client.IO.socket(IO.java:37)
at com.github.nkzawa.socketio.client.IO.socket(IO.java:33)
at com.xx.deneme.MainW.(MainW.java:74)
at com.xx.deneme.MainW.main(MainW.java:63)
Caused by: java.lang.ClassNotFoundException: org.json.JSONException
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 6 more

socket.io compatiblity : unhandled socket.io url

Hi, I try to use your library to connect a java client to a node js with socket.io.

But I got any error on client part and nothing happen.

But on nodejs server I received: unhandled socket.io url until my client stops

It seems you library is comptaible with socket.io < 0.7 ?

on ack callback

The function com.github.nkzawa.emitter.Emitter.emit() has an ack parameter. So you can let the server issue a callback which gets executed client side.

Is there a similar way to it the other way around?, so on the client-side:

socket.on("event-from-server", new Emitter.Listener() {
public void call(Ack ack, Object... args) {
ack.call();
});
});

How to let the client send a callback after receiving a message from the server

Hi, I was wondering how do I make a callback on the client side to acknowledge the server.
for example,
Assuming the server side has this:
io.sockets.emit('delete', {id: id}, function(data){
console.log('callback');
});

And on the client side ( I'm using Android ), I have

socket.on("delete", new Emitter.Listener() {
@OverRide
public void call(Object... args) {
log.d(TAG,"Received server delete msg");
}

My question is, is there a way to ack the server similar to the regular java script?
If it's In java script, I could do something like this
socket.on('delete', function(data, callback) {
console.log("i received: "+ data);
callback("This function on server will run");
});

Thank you.

SSLEngine

How can I set a custom SSLEngine? I'm websocket transport and self signed certificate and I did not find a solution.

Secure websockets not working

Secure websockets are not working.

I'm using OpenShift to host a node server as websocket endpoint for an android application.

When connecting to node and using http the connection is successfully upgraded to websockets. But when using https (wildcard cert by openshift) I cannot successful upgrade the connection to websockets but android app will always use polling (verified on node server log).

Accessing Engine.IO transport from Socket.IO

First of all, thank you for your great library.

Your Engine.IO client library supports event handlers in transport layer, so library users can set headers (e.g. Cookie) when opening a connection.

https://github.com/nkzawa/engine.io-client.java#extra-features-only-for-java-client

I'd like to do the same with this Socket.IO library. But unfortunately it's not supported to add event handlers in the Engine.IO layer.

I just modified Manager's #open() method as follows, and the code worked as I expected.

https://github.com/nkzawa/socket.io-client.java/blob/socket.io-client-0.1.2/src/main/java/com/github/nkzawa/socketio/client/Manager.java#L219

final com.github.nkzawa.engineio.client.Socket socket = Manager.this.engine;
socket.on(Engine.EVENT_TRANSPORT, new Listener() {
    @Override
    public void call(Object... args) {
        Transport transport = (Transport)args[0];
        transport.on(Transport.EVENT_REQUEST_HEADERS, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                @SuppressWarnings("unchecked")
                Map<String, String> headers = (Map<String, String>)args[0];
                // send cookies to server.
                headers.put("Cookie", "foo=1;");
            }
        }).on(Transport.EVENT_RESPONSE_HEADERS, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                @SuppressWarnings("unchecked")
                Map<String, String> headers = (Map<String, String>) args[0];
                // get cookies from server.
                String cookie = headers.get("Set-Cookie");
            }
        });
    }
});

I have two questions:

  • Is accessing Engine.IO transport layer from Socket.IO library prohibited by design?
  • If not, what do you think about more extra features to customize headers? Any suggestions about new APIs?

Actually I'm a newbie of Socket.IO. If these questions miss the point, I'm sorry to bother you.

Caused by: java.net.ConnectException: Connection refused: connect

socket = new SocketIO();
socket.connect("http://10.0.0.71:9092", this);// local ip address

    // Sends a string to the server.
    socket.send("Hello Server");

    // Sends a JSON object to the server.
    socket.send(new JSONObject().put("key", "value").put("key2",
            "another value"));

    // Emits an event to the server.
    socket.emit("event", "argument1", "argument2", 13.37);
}

While using this code for creating server connection and by using socket.io.jar.

I get the following error
io.socket.SocketIOException: Error while handshaking
at io.socket.IOConnection.handshake(IOConnection.java:322)
at io.socket.IOConnection.access$600(IOConnection.java:39)
at io.socket.IOConnection$ConnectThread.run(IOConnection.java:199)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)

Reconnect problem

I have a service that when start:

private void connect() {
LogUtil.i("Conectando com o SocketIO");
socketIO.connect();
}

and when finish:

private void disconnectIOSocket() {
if ( socketIO != null ) {
socketIO.close();
socketIO.disconnect();
}
}

Everything are working great but when i stop the service and try to connect again nothing happen after the command:

socketIO.connect();

No data for an ack causes an exception

Code:

ack.call();

Error:

    java.util.MissingFormatArgumentException: Format specifier: s
            at java.util.Formatter.getArgument(Formatter.java:1111)
            at java.util.Formatter.doFormat(Formatter.java:1076)
            at java.util.Formatter.format(Formatter.java:1042)
            at java.util.Formatter.format(Formatter.java:1011)
            at java.lang.String.format(String.java:1988)
            at java.lang.String.format(String.java:1962)
            at com.github.nkzawa.socketio.client.Socket$6.call(Socket.java:284)

Ack without params causes MissingFormatArgumentException

Ack ack = (Ack) args[0];
ack.call();

This code causes an exception:

    java.util.MissingFormatArgumentException: Format specifier: s
            at java.util.Formatter.getArgument(Formatter.java:1111)
            at java.util.Formatter.doFormat(Formatter.java:1076)
            at java.util.Formatter.format(Formatter.java:1042)
            at java.util.Formatter.format(Formatter.java:1011)
            at java.lang.String.format(String.java:1999)
            at java.lang.String.format(String.java:1973)
            at com.github.nkzawa.socketio.client.Socket$6.call(Socket.java:284)

The workaround is always send new JSONObject().

Error While debugging:

Hello Im getting this error in console while debugging:

I added this compile 'com.github.nkzawa:socket.io-client:0.2.0' on build.gradle because im using android studio.

Error:Execution failed for task ':app:dexDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    C:\Users\Erick\AppData\Local\Android\android-studio\sdk\build-tools\android-4.4W\dx.bat --dex --num-threads=4 --output D:\ProjectsImportedFromEclipse\WebSocketChat\app\build\intermediates\dex\debug D:\ProjectsImportedFromEclipse\WebSocketChat\app\build\intermediates\classes\debug D:\ProjectsImportedFromEclipse\WebSocketChat\app\build\intermediates\dependency-cache\debug D:\ProjectsImportedFromEclipse\WebSocketChat\app\build\intermediates\pre-dexed\debug\engine.io-client-0.3.0-443924d78a72e7b325e51936fe74a87663e8ed9e.jar D:\ProjectsImportedFromEclipse\WebSocketChat\app\build\intermediates\pre-dexed\debug\Java-WebSocket-1.3.0-f5c76730c2d6cdc8a3bf4d71ea67b620d48f79eb.jar D:\ProjectsImportedFromEclipse\WebSocketChat\app\build\intermediates\pre-dexed\debug\socket.io-client-0.2.0-2af807c83fbcf6a233217dffd53396f16924dc3f.jar D:\ProjectsImportedFromEclipse\WebSocketChat\app\build\intermediates\pre-dexed\debug\socketio-4e8d5dc694f956d686faa67307203cdfde9fb0af.jar
Error Code:
    2
Output:
    UNEXPECTED TOP-LEVEL EXCEPTION:
    com.android.dex.DexException: Multiple dex files define Lorg/java_websocket/WebSocketListener;
        at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:594)
        at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:552)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:533)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:170)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:188)
        at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439)
        at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287)
        at com.android.dx.command.dexer.Main.run(Main.java:230)
        at com.android.dx.command.dexer.Main.main(Main.java:199)
        at com.android.dx.command.Main.main(Main.java:103)

This is what im executing on my activity.

        Socket socket = null;
        try {
            socket = IO.socket("http://192.168.1.30:3000");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                //socket.emit("foo", "hi");
                //socket.disconnect();
            }

        }).on("event", new Emitter.Listener() {

            @Override
            public void call(Object... args) {}

        }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

            @Override
            public void call(Object... args) {}

        });
        socket.connect();

unhandled socket.io url error

Hi,

I am trying to use this library to connect to a "socket.io" instance running on node.js server.

The port on which node.js is running is 8000.
However when I try to run the code from the Java implementation on the client side, I get an error on the server side saying: "info:unhandled socket.io url"

Here is my code on the client side:

    socket = IO.socket("http://godel.ece.vt.edu:8000");


    socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
      @Override
      public void call(Object... args) {
        System.out.println("coming");
        socket.emit("foo", "hi");
        socket.disconnect();
      }

    }).on("message"
            , new Emitter.Listener() {

      @Override
      public void call(Object... args) {}

    }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

      @Override
      public void call(Object... args) {}

    });

    socket.connect();

    System.out.println("done");

    socket.on("message", new Emitter.Listener() {
          @Override
          public void call(Object... args) {
            JsonObject obj = (JsonObject)args[0];
            System.out.println(obj.toString());
          }
        });

Is there a way I can resolve this?

マルチバイト文字が文字化けする(?)

いわゆるチャットアプリを作っていて、WebブラウザとAndroidでチャットする前提なのですが、ブラウザ同士だと文字化けしない(socket.io-client.javaは噛まないので)んだけど、socket.io-client.javaを使ったAndroidとチャットするときは、マルチバイト文字部分だけ文字化けします。

・Androidから送信したマルチバイト文字(UTF8)をサーバ側でconsole.logすると、化けている
・サーバ内に文字列リテラル(UTF8)として定義してある文字をAndroidで受信すると化けている
・でも、化ける時と化けない時がある

化けるときの条件がよくわかってないのと、socket.io-client.java側じゃなくて、他のライブラリのせいで化けてる可能性もあるので、検証用のコード書いてみます。

送信と受信は特定のスレッドに縛られる?

issueというか、仕様確認みたいな感じですが、connect()するスレッドはUIスレッドに縛られるのですよね?(UIスレッド以外からの場合は例外が出たので)

emit()するスレッドと、on()で登録したイベントを受け取るスレッドは、何かに縛られるのでしょうか?

実は、サーバからブロードキャストした時に、Webクライアントは受信できるけどAndroidは受信できないとか、Androidからemit()してサーバでそれをそのまま返信しているけどAndroid側では受信できない、などの現象が起こっていて、原因をつかめずに居ます。

効率化のためemit()するスレッドを新たに起こしたり、Emitter.Listener.call()からスレッドを起こしたり起こさなかったり、しているのですが、この当たりが不安定になっている原因なのかなぁとも思いまして。

以下の3点について想定している使い方は何になるでしょうか?
・connect()を呼べるスレッドは縛りがありますか?
・onEmit()を呼べるスレッドは縛りがありますか?
・Emitter.Listener.call()を呼ぶスレッドは何?(UIスレッド? UIスレッド以外のスレッド? onEmit()を呼んだスレッドと関係ある?)

how to getting message from server

Hi.
how can i get message from server?
this is the server:

var fs = require('fs');

var server;
if (process.env.SSL) {
server = require('https').createServer({
key: fs.readFileSync(__dirname + '/key.pem'),
cert: fs.readFileSync(__dirname + '/cert.pem')
});
} else {
server = require('http').createServer();
}

var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
var nsp = process.argv[2] || '/';
var slice = Array.prototype.slice;

io.of(nsp).on('connection', function(socket) {
socket.send('hello client');

io.on('connection', function(socket){
socket.broadcast.emit('hi');
});

socket.on('message', function() {
var args = slice.call(arguments);
socket.send.apply(socket, args);
});

socket.on('echo', function() {
var args = slice.call(arguments);
socket.emit.apply(socket, ['echoBack'].concat(args));
});

socket.on('ack', function() {
var args = slice.call(arguments);
var callback = args.pop();
callback.apply(null, args);
});

socket.on('callAck', function() {
socket.emit('ack', function() {
var args = slice.call(arguments);
socket.emit.apply(socket, ['ackBack'].concat(args));
});
});

socket.on('getAckDate', function(data, callback) {
callback(new Date());
});

socket.on('disconnect', function() {
console.log('disconnect');
});

socket.on('error', function() {
console.log('error: ', arguments);
});
});

server.listen(port, function() {
console.log('Socket.IO server listening on port', port);
});

Handling Connection timeout Error

I have a problem with an error like this one written below:

Fatal Exception: java.lang.AssertionError
java.net.SocketTimeoutException: failed to connect to host/ip port after 90000ms: isConnected failed: ETIMEDOUT (Connection timed out)

Is there any idea to handle this Exception?
Thanks

Is chatroom namespace supported ?

I want to connect from android to a chatroom;

// server code
io.of("/urucas-sting")
   .on('connection', function(socket){
    console.log("user connected");
    socket.broadcast.emit("new user");
 });

// web code
var socket = io.connect("/urucas-sting");
// android code
 socket = IO.socket("http://sting.jit.su/urucas-sting");

The web connection works perfect, but i'm not receiveing any action from android, is this code correct ? Or how do I connect to an specific chatroom ?

not support Chinese character

when I use server to send Chinese character , like follow:

socket.emit('message', '你好');  // '你好' mean 'hello' in english :D

but the client can not receive the message.

in version 0.1.3

socket.io and android not connecting a second time

I'm using socket.io and android. I install the app and it will connect to my server perfectly on the first launch. However, when I exit the app and open it again it will not reconnect to the server.

I notice I get the debug line
new io instance for http://tyr-einsteinium.rhcloud.com:80/
only when the app is run for the first time after install.

Am I not disconnecting from the socket properly? Is there some sort of clean up I need to do when I exit to ensure that I can reconnect to the server when I launch the app again?

Is it possible to execute a callback function in the "on" event ?

Hello, from the Socket.IO doc, we can do the following:

One side :

socket.on('ferret', function (name, fn) {
   fn('woot');
});

The other side :

socket.emit('ferret', 'tobi', function (data) {
  console.log(data); // data will be 'woot'
});

Is it possible to do the same "on" event with the java client? (without having to emit a new event) :

socket.on("ferret",new Emitter.Listener() {

  @Override
  public void call(Object... objects) {
    String response = "woot";
    // How to send back "woot" now? is one of the objects a function to cast ?
 }
});

Thanks

second connection in child shell

is it possible to open new socket connection on child shell ? trying to connect like this while parent shell connected but nothing happens.

public chatWindow(Shell shell, final String room_id2) throws URISyntaxException {
super(shell, SWT.CLOSE | SWT.SHADOW_IN | SWT.NO_FOCUS);
setLayout(new FillLayout(SWT.HORIZONTAL));

    Composite composite = new Composite(this, SWT.NONE);

    text = new Text(composite, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI);
    text.setLocation(0, 0);
    text.setSize(300, 157);
    createContents();

    final Socket socketx = IO.socket("http://xxxxx:3000");


    socketx.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

      @Override
      public void call(Object... args) {
      System.out.println("asdasd2");
      JSONObject obj = new JSONObject();
      try {
        obj.put("id", room_id2);
        obj.put("connected_user", "emek");
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
        socketx.emit("room", obj);
      }

How to get connection errors

During the connection phase the Socket.on(Socket.EVENT_ERROR, new Emitter.Listener()) is not called. All errors are not logged, not send to this method, it is a little bit voodoo and without debugger you cannot get it. I found the Manager is able to do by events Manager.EVENT_CONNECT_ERROR and Manager.EVENT_CONNECT_TIMEOUT. The only problem is, the manager is a private API. I wrote a new IO.java that returns Socket and Manager, but I don't know if this is good solution. From my point of view it will be better to create Socket#getManager() (there is it field) or propagate these events to the socket too. Or am I wrong and miss something?

How can I connect if client is behind proxy?

In my case, android application is behind the proxy server and it needs to connect to the socket.io server. How can I handle this case? Does this library automatically handles this case? I was not able to know this from the example code given. Kindly, let me know if it is possible for android behind proxy to connect to socket.io server using this library. If not, just let me know what should be changed in the code to do so. Thanks

Thank you!

I just wanted to say thank you for this fantastic library, it made life very easy for me. I'm curious, do you plan to introduce a socket.io-stream.java implementation in the near future?

android mobile Lock screen is disconnect

hi
I am connecting to the server using the following code:
socket = IO.socket(adress);
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

                  @Override
                  public void call(Object... args) {
                    try {
                        socket.emit("tag", new String(uid), new MyCallBack());
                        application.setClient(socket);
                        connecting = true ;

                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally{
                        starting = false ;
                    }}
                });

but After a while the phone lock screen
The server socket is disconnect,The client is not active disconnect,but client not callback
I am disconnect callback to the server using the following code:
socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

                      @Override
                      public void call(Object... args) {
                          connecting = false ;
                      }
                    });

I want to know how to automatically disconnect this socket
Whether the socket heartbeat to maintain themselves
thanks

Error in Android applications

When I try to open connection to http socket.io server. An exception is thrown by Dalvik :

"Could not find class 'com.gitgub.nkzawa.engineio.client.transports.WebSocket$1" referenced from method com.github.nkzawa.engineio.client.transport.WebSocket.doOpen

From java application run correctly.

emit message & callback methods

Hi,
I am experiencing some problems using socket.io-client.java with netty-socketio server.

I am connecting to the server using the following code:

                           IO.Options opts = new IO.Options();
            opts.forceNew = true;

            socket = IO.socket("http://games4.web2mil.com:8281/", opts);

            socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
                  @Override
                   public void call(Object... args) {
                           socketIo.disconnect();
            }
                          });

I make a connection but the Socket.EVENT_CONNECT event is never called. If I change the method listening to socket.io().on(Manager.EVENT_OPEN, new Emitter.Listener() { , the method is invoked when the socket connects. What is the difference between Socket.EVENT_CONNECT and Manager.EVENT_OPEN? why is Socket.EVENT_CONNECT not invoked?

I am also having problems when emitting messages from client to server, I am emitting messages using the following code: socket.emit("method listening in server side", messsage). Do you have any idea why this is not working?

Thanks,

Cant connect to 192.168.0.100:8006

I cant manage to connect to a local url,

socket = IO.socket("http://192.168.0.100:8006/");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
  @Override
  public void call(Object... args) {
    Log.i(TAG_NAME, "connected");
  }
});
socket.on(Socket.EVENT_ERROR, new Emitter.Listener() {
  @Override
  public void call(Object... args) {
    Log.i(TAG_NAME, "error");
  }
});
socket.connect();

i'm getting Socket.EVENT_ERROR and Socket.EVENT_CONNECT_TIMEOUT.

How can I debug this errors on:

socket.on(Socket.EVENT_ERROR, new Emitter.Listener() {
  @Override
  public void call(Object... args) {
    Log.i(TAG_NAME, "error");
    Log.i(TAG_NAME, args.toString());
  }
});

?

id and username attributes

Hi.
in the Automattic/socket.io-client we can access to id attribute with socket.io.engine.id.
how can i do this in socket.io-client.java?
thanks dear nkzawa.

OnReconnect does not set connected to true on Socket and disconnects from that point stop working

https://github.com/nkzawa/socket.io-client.java/blob/master/src/main/java/com/github/nkzawa/socketio/client/Socket.java#L388

That check is not always updated, my guess is reconnection do not fire the Packet Connected and that cause that when you call disconnect nothing happens and the server is still waiting for that websocket to connect again.

The issue is you create a socket -> connect -> disconnect, everything works, then you again connect (the package Connect is not send therefor the connected flag stays to false and the client connects, from that moment even if you call disconnect it will be ignored because this flag.

Regards

Unable to connect, no exception and timeout.

Hello,
thanks for sharing this socket.io 1.0+ client for java. but.. I cannot connect to my socket.io server, strangely, there's no exception and timeout, not received any response to my device. (I'm using SM-N900S, Android OS 4.4.2) I tried to solve this problem, but there's no solution to fix this, finally I decided to create this issues in order to help ..

I included socket.io-client:0.1.1 version.
repositories {
mavenCentral()
}

dependencies {
compile group: 'com.github.nkzawa', name: 'socket.io-client', version: '0.1.1'
}

This is my activity java file,
https://gist.github.com/ejnahc/c28dbce4773df39dd506

..and Here's android debug log.
https://gist.github.com/ejnahc/9f79a3d3820d7413200e

I'm using this example for socket.io server (socket.io 1.0.4), and it works via web client (Google Chrome).
https://github.com/guille/chat-example.git

Of course I added android.permission.INTERNET to AndroidManifest.xml.

please give me a helping hand, I'm looking forward to your reply.
thank you :)

No possible to connect or get some error, just 1000+ requests

try {
Socket socket = IO.socket("http://192.168.3.100:8000");
socket.on(Socket.EVENT_ERROR, new Emitter.Listener() {
@OverRide
public void call(Object... args) {
Object arg = args[0];
Log.i("SOCKETIO", "error: " + (arg != null ? arg.toString() : ""));
}
});
socket.connect();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

192.168.3.103 - - [2014-08-31 08:54:22] "GET /socket.io/?EIO=3&transport=polling HTTP/1.1" 200 158 0.001698
192.168.3.103 - - [2014-08-31 08:54:22] "GET /socket.io/?EIO=3&transport=polling HTTP/1.1" 200 158 0.001080
192.168.3.103 - - [2014-08-31 08:54:22] "GET /socket.io/?EIO=3&transport=polling HTTP/1.1" 200 158 0.001108
192.168.3.103 - - [2014-08-31 08:54:22] "GET /socket.io/?EIO=3&transport=polling HTTP/1.1" 200 158 0.001145
192.168.3.103 - - [2014-08-31 08:54:22] "GET /socket.io/?EIO=3&transport=polling HTTP/1.1" 200 158 0.001072
192.168.3.103 - - [2014-08-31 08:54:22] "GET /socket.io/?EIO=3&transport=polling HTTP/1.1" 200 158 0.001219
192.168.3.103 - - [2014-08-31 08:54:22] "GET /socket.io/?EIO=3&transport=polling HTTP/1.1" 200 158 0.001096
192.168.3.103 - - [2014-08-31 08:54:22] "GET /socket.io/?EIO=3&transport=polling HTTP/1.1" 200 158 0.001041
192.168.3.103 - - [2014-08-31 08:54:22] "GET /socket.io/?EIO=3&transport=polling HTTP/1.1" 200 158 0.001074
192.168.3.103 - - [2014-08-31 08:54:23] "GET /socket.io/?EIO=3&transport=polling HTTP/1.1" 200 158 0.001475
192.168.3.100 - - [2014-08-31 08:55:28] "GET /socket.io/?EIO=3&transport=polling HTTP/1.1" 200 158 0.004009
192.168.3.100 - - [2014-08-31 08:55:39] "GET /socket.io/?EIO=3&transport=polling HTTP/1.1" 200 158 0.004575

Adding dependency into Android Studio

I have problem when I try to add the this dependencies into Android Studio gradle

compile 'com.github.nkzawa:socket.io-client:0.1.2'

But when I try to build, it display error in the message gradle build

Warning:Dependency org.json:json:20090211 is ignored for release as it may be conflicting with the internal version provided by Android.
In case of problem, please repackage with jarjar to change the class packages

Anyone knows how to get this solved???

can not receive event by room emit

by socket.io doc

Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id. For your convenience, each socket automatically joins a room identified by this id.

So We can send message to specified user by using:

server code

io.to('socket_id').emit('message', 'hello')

I try to use socket.io-client.js to test, it works, It can receive message.

But not work for this library.

thanks for your work 👍

Parser error is occurred while decoding UTF8 in com.github.nkzawa.engineio.parse

Hi, My server is using a socket.io 1.1.0 version with node.js.
But an error is occurred while decoding UTF8. In this case the characters are Korean and json string.
The error log is below

e = {com.github.nkzawa.utf8.UTF8Exception@831697484872}"com.github.nkzawa.utf8.UTF8Exception: Invalid continuation byte"
err = {com.github.nkzawa.engineio.parser.Packet@831695820048}
data = {java.lang.String@831695810408}"parser error"
type = {java.lang.String@831696549528}"error"

How can i solve this problem? please help me T.T

Thanks

Listening all events.

It seems i can't actually scan all events through the socket if I don't know their names.
Example :
serverSide :
socket.emit("event1","hello");
socket.emit("event2"," world !");

ClientSide i have to proceed this way :

socket.on("event1", new Emitter.Listener(){
    public void call(Object... args){
        System.out.print(args[0]);
    }
}).on("event2", new Emitter.Listener(){
    public void call(Object... args){
        System.out.print(args[0]);
    }
}

I have to define a method 'on' for event1 and event2.
I'd like to get a way to do it like this (or in a similar way) :

socket.onEvent(new Emitter.Listener(){
    public void call(Object... args){
        System.out.println(args);
    }
}

so the output looks like this way :

{"event1", { "hello" } }
{"event2", { " world !"} }

but i have not to know event1 and event2 for listening the socket, even it is noisy.
Maybe i don't get the proper way to do it. If that so i apologize.

isConnected on Socket

I see the Socket has private connected field, but it has no getter. It would be nice to have a getter for it.

Unable to connect using https

/I am using node.js server side and android and another node.js client side web application.
The wep application is able to connect securely while the android application is just giving an timeout error.
/

//The code for creating sslcontext
Log.d(TAG,"setupContext");
//Using a client certificate
String password = "password"
KeyStore keyStore = KeyStore.getInstance("PKCS12");
InputStream is = context.getResources().openRawResource(R.raw.client_crt);
keyStore.load(is, password.toCharArray());
is.close();

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    kmf.init(keyStore, password.toCharArray());
    KeyManager[] keyManagers = kmf.getKeyManagers();

    // Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or ...)
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    // Using self signed certificate
    is = context.getResources().openRawResource(R.raw.cacert);
    InputStream caInput = new BufferedInputStream(is);
    Certificate ca;
    ca = cf.generateCertificate(caInput);
    Log.i(TAG,"ca=" + ((X509Certificate) ca).getSubjectDN());
    caInput.close();


    // Create a KeyStore containing our trusted CAs
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);
    trustStore.setCertificateEntry("ca", ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
    tmf.init(trustStore);
    TrustManager[] trustManagers =  tmf.getTrustManagers();

    // Create an SSLContext that uses our TrustManager
    SSLContext sslcontext = SSLContext.getInstance("TLS");

    sslcontext.init(keyManagers, trustManagers, null);

    IO.Options opts = new IO.Options();
    opts.forceNew = true;
    opts.reconnection = false;
    opts.sslContext = mSslContext;
    opts.secure=true;
    mSocket = IO.socket("https://" + mIpAddress + ":" + mPort+"/", opts);
    mSocket.connect();
    mSocket.on(Socket.EVENT_CONNECT, mConnectionListener);
    mSocket.on(Socket.EVENT_DISCONNECT,mDisconnectionListener);
    mSocket.on(Socket.EVENT_ERROR,mErrorListener);
    mSocket.on(Socket.EVENT_MESSAGE,mMessageListener);
    mSocket.on(Socket.EVENT_CONNECT_ERROR,mConnectionErrorListener);

     // I never get call for EVENT_CONNECT

///////////////////////////SERVER CODE///////////////////////////////////////////////
var privateKey = fs.readFileSync('certificates/server.key').toString();
var certificate = fs.readFileSync('certificates/server.crt').toString();
var ca = fs.readFileSync('certificates/cacert.pem').toString();
// Sending and receiving events with Socket.IO
var app = express();
https.globalAgent.options.rejectUnauthorized = false;
var server = https.createServer({key:privateKey,cert:certificate,ca:ca },app);
// var server = require('http').Server(app);
exports.io = require('./sockets').listen(server);
//Server is listening on port 3000

Please tell a way to enable logs in android app for socket.io and possible cause of this problem.
There is no activity in node.js terminal as if the socket never got a call after using https it work fine if I use http
Thanks and regards,
Anshul

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.