GithubHelp home page GithubHelp logo

socket.io-java-client's People

Contributors

fatshotty avatar gottox avatar holic avatar ixalon 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-java-client's Issues

Fix for IllegalStateException: Timer was canceled

Apparently cleanup() is called before transportDisconnected() and the second cleanup() call from reconnect() throws the exception. Also, you can't call disconnect() in onError(), or that will also cause a problem (and you don't need to). Hopefully, this will fix the issue:

diff --git "a/C:\\Users\\WxAp\\AppData\\Local\\Temp\\TortoiseGit\\IOCDCF7.tmp\\IOConnection-8f4c6b7-left.java" "b/C:\\ExternalLibs\\sources\\socket.io-java-client\\src\\io\\socket\\IOConnection.java"
index 420d0cc..3dc207b 100644
--- "a/C:\\Users\\WxAp\\AppData\\Local\\Temp\\TortoiseGit\\IOCDCF7.tmp\\IOConnection-8f4c6b7-left.java"
+++ "b/C:\\ExternalLibs\\sources\\socket.io-java-client\\src\\io\\socket\\IOConnection.java"
@@ -555,7 +555,7 @@ class IOConnection implements IOCallback {
     */
    public void transportDisconnected() {
        this.lastException = null;
-       setState(STATE_INTERRUPTED);
+       if (getState() != STATE_INVALID) setState(STATE_INTERRUPTED);
        reconnect();
    }

@@ -568,7 +568,7 @@ class IOConnection implements IOCallback {
     */
    public void transportError(Exception error) {
        this.lastException = error;
-       setState(STATE_INTERRUPTED);
+       if (getState() != STATE_INVALID) setState(STATE_INTERRUPTED);
        reconnect();
    }

Maven support ?

Hello we use your project for an open source development (Hubiquitus) but we can not found your project in the maven central repository.
Can you tell us if you can add the maven support for you project ?

SSL Connection in websocket mode does not work.

I could connect to both web-socket and Xhr transport in HTTP mode. But when i switch to HTTPS only Xhr mode is working. i used the default SSL Context as below

SocketIO.setDefaultSSLSocketFactory(SSLContext.getInstance("Default"));
This works fine in Xhr mode. But in websocket transport there are no responses or errors.

It's a bug?

My server side is both hold socket.io and http, when i run this, it just visit the http server?

Should we add a user guide to readme.md?

Here is what i write to help myself when use your library to android project.

build socket.io client to android projects

  1. goto socket.io-java-client project and run 'ant jar' to get jar/socketio.jar
  2. copy the jar/socketio.jar to libs of android project
  3. refresh the android project on eclipse

'ant jar' doesn't build

Following the instruction on README, doing 'ant jar' I'm currently getting the following:

BUILD FAILED
Target "jar" does not exist in the project "socket.io-java-client". 

Can't disconnect xhr socket

I'm trying to disconnect the socket when the user logs out. throws following error.
java.lang.IllegalStateException: Timer was canceled
at java.util.Timer.scheduleImpl(Timer.java:561)
at java.util.Timer.schedule(Timer.java:459)
at io.socket.IOConnection.reconnect(IOConnection.java:766)
at io.socket.IOConnection.transportDisconnected(IOConnection.java:559)
at io.socket.XhrTransport$PollThread.run(XhrTransport.java:131)

socket connection is in xhr mode. trying to disconnect as socket.disconnect();

server reconnection issue

Hi guys, I ran into an issue with the server reconnection. When the server goes down and then comes up again I get this exception on the client:

I/io.socket(  333): < 7:::1+0
I/System.out(  333): an Error occured
W/System.err(  333): io.socket.SocketIOException: 1+0
W/System.err(  333):    at io.socket.IOConnection.transportMessage(IOConnection.java:736)
W/System.err(  333):    at io.socket.WebsocketTransport.onMessage(WebsocketTransport.java:82)
W/System.err(  333):    at org.java_websocket.client.WebSocketClient.onWebsocketMessage(WebSocketClient.java:361)
W/System.err(  333):    at org.java_websocket.WebSocketImpl.deliverMessage(WebSocketImpl.java:565)
W/System.err(  333):    at org.java_websocket.WebSocketImpl.decodeFrames(WebSocketImpl.java:331)
W/System.err(  333):    at org.java_websocket.WebSocketImpl.decode(WebSocketImpl.java:152)
W/System.err(  333):    at org.java_websocket.client.WebSocketClient.interruptableRun(WebSocketClient.java:247)
W/System.err(  333):    at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:193)
W/System.err(  333):    at java.lang.Thread.run(Thread.java:1019)
I/io.socket(  333): Cleanup

how to build server side

i want to use your code at android,but i do not know how to build server side,can you give some detail info.thank you

ICS Jelly Bean support

Hey there guys would like to know if someone have use this library sucessfully with ics or jelly bean android project

ConcurrentModification as IOConnection.register() does not take a lock

The for-loop
for (IOConnection connection : list)
in that method throws ConcurrentModificationExceptions, when I create hundreds of client instances (for benchmarking purposes).

I haven't yet familiarized myself with the codebase, but when I just put a
synchronized (connections)
around the full body of that method (which is maybe too coarse) it worked fine.

FYI: In cleanup(), you already synchronize on the connections object in order to access it

What was the problem with Java-Websocket?

Hey there @Gottox!

I am the author of Java-WebSocket. It looks like you were originally using that for this Socket.io client lib. Very Cool!

Then it looks like you switched to Weberknecht at some point. Basically I'm just curious as to why you made the switch. What was the problem with Java-WebSocket? We would love to accomodate whatever your needs are.

Cheers!

xhr polling doesn't work

In my server, I have to limit socket.io to xhr-polling only (in order to support MSIE):

    io.set("transports", ["xhr-polling"]);

When I do this, the Java client cannot connect to the server - the server sees that a new client connects, however, the client gets no messages from the server.

Maven repos

Hello there,

There will be a maven repository for this lib?

Thanks

Any way to set some custom headers?

It would be really useful for me to be able to pass in some custom headers during the connection. This is something that could be read on the authorization event on socket io? Any way to do this?

Possible concurrent problem in multi-thread

I want to use this lib in a multiple thread environment. I will create multiple SocketIO to connect the server, and send and get message.
I checked the code to create connection, but I found it is possible to have a concurrent problem if I have many thread trying to create SocketIO object at the same time.

The related code is as below:
static public IOConnection register(String origin, SocketIO socket) {

             //it is not synchronized, so there will be problem.
    List<IOConnection> list = connections.get(origin); 
    if (list == null) { 
        list = new LinkedList<IOConnection>();
        connections.put(origin, list);
    } else {
        synchronized (list) {
            for (IOConnection connection : list) {
                if (connection.register(socket))
                    return connection;
            }
        }
    }

    IOConnection connection = new IOConnection(origin, socket);
    list.add(connection);
    return connection;
}

Error while reconnecting

Hi there,

I have my socket.io client connected to my socket.io nodejs server. Everything works ;)

After same changes on my nodejs server code, I perform a deploy on the remote server.
I'm using capistrano for deploying, so the nodejs server will be shutdown and restarted again in a few seconds.

Unfortunately Socket.io-java client will get error and will not perform a new connection :(
I investigated and I found the reason (hope can help)

Here is the method that wants to perform a new connection.
https://github.com/Gottox/socket.io-java-client/blob/master/src/io/socket/WebsocketTransport.java#L129

Unfortunately the code (in weberknecht internally) throws an ArrayIndexOutOfBoundException and the code in Socket.io-java client doesn't catch the exception. So, in this case the TimerThread will exit without give us the possibility to catch it. :(

I think the correct code is implemented here:
https://github.com/Gottox/socket.io-java-client/blob/master/src/io/socket/WebsocketTransport.java#L78

catching all generic Exception, socket.io-java client should be able to skip the fatal exception and try again reconnecting.

Hope this can help ;)

Hangs CPU and takes whole mem

When I call socket.connect(callback) my java process starts to eat 100% cpu and everything starts lagging.

Implemented methods in callback are empty, so, i'm just connecting and i don't do anything else.

Jar File - not working

I do not know if this is a bug or a java limitation due to security.

but when i run my app in eclipse it connects to socket.io OK, but when i run a Jar file it gives an error. I have identified the problem but i'am not able to resolve it.

The problem (i think) is in this line:
InputStream stream = connection.getInputStream(); [IOConnection.java]

i'm trying to connect to an ip that is not 'localhost'.

i have also an android version, and Strangely it works ok in android.

java.lang.IllegalStateException: Timer was canceled

Could not figure out how this happened. Sorry. This is the error log.

java.lang.IllegalStateException: Timer was canceled
at java.util.Timer.scheduleImpl(Timer.java:561)
at java.util.Timer.schedule(Timer.java:459)
at io.socket.IOConnection.reconnect(Unknown Source)
at io.socket.IOConnection.transportDisconnected(Unknown Source)
at io.socket.WebsocketTransport.onClose(Unknown Source)
at org.java_websocket.client.WebSocketClient.onWebsocketClose(Unknown Source)
at org.java_websocket.WebSocketImpl.closeConnection(Unknown Source)
at org.java_websocket.WebSocketImpl.closeConnection(Unknown Source)
at org.java_websocket.WebSocketImpl.close(Unknown Source)
at org.java_websocket.WebSocketImpl.close(Unknown Source)
at org.java_websocket.client.WebSocketClient.interruptableRun(Unknown Source)
at org.java_websocket.client.WebSocketClient.run(Unknown Source)
at java.lang.Thread.run(Thread.java:856)

android connection

I use the client in java program to connect socket.io, it works well, very great job. But when I tried it in android emulator, it seems not work and responses nothing.I wonder why this happen?

io.socket.SocketIOException: Error while handshaking

I just followed the instructions but I'm getting
following exception:

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.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Long.parseLong(Long.java:431)
at java.lang.Long.parseLong(Long.java:468)
at io.socket.IOConnection.handshake(IOConnection.java:318)
... 2 more
26 Mar, 2013 7:04:21 PM io.socket.IOConnection cleanup
INFO: Cleanup

Missing org.java_websocket.client dependency

(after 594a0e5, which switched from Weberknecht to Java-Websockets)

(The workaround is to build @ b01ff2c (previous commit) or add the dependency.)

drhop@hexxer:~/dev/otartc/third_party/socket.io-java-client$ ant jar
Buildfile: /home/drhop/dev/otartc/third_party/socket.io-java-client/build.xml

init:
[mkdir] Created dir: /home/drhop/dev/otartc/third_party/socket.io-java-client/bin

build-project:
[echo] socket.io-java-client: /home/drhop/dev/otartc/third_party/socket.io-java-client/build.xml
[javac] /home/drhop/dev/otartc/third_party/socket.io-java-client/build.xml:40: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
[javac] Compiling 9 source files to /home/drhop/dev/otartc/third_party/socket.io-java-client/bin
[javac] /home/drhop/dev/otartc/third_party/socket.io-java-client/src/io/socket/WebsocketTransport.java:11: package org.java_websocket.client does not exist
[javac] import org.java_websocket.client.DefaultSSLWebSocketClientFactory;
[javac] ^
[javac] /home/drhop/dev/otartc/third_party/socket.io-java-client/src/io/socket/WebsocketTransport.java:12: package org.java_websocket.client does not exist
[javac] import org.java_websocket.client.WebSocketClient;
[javac] ^
[javac] /home/drhop/dev/otartc/third_party/socket.io-java-client/src/io/socket/WebsocketTransport.java:13: package org.java_websocket.handshake does not exist
[javac] import org.java_websocket.handshake.ServerHandshake;
[javac] ^
[javac] /home/drhop/dev/otartc/third_party/socket.io-java-client/src/io/socket/WebsocketTransport.java:15: cannot find symbol
[javac] symbol: class WebSocketClient
[javac] class WebsocketTransport extends WebSocketClient implements IOTransport {
[javac] ^
[javac] /home/drhop/dev/otartc/third_party/socket.io-java-client/src/io/socket/WebsocketTransport.java:86: cannot find symbol
[javac] symbol : class ServerHandshake
[javac] location: class io.socket.WebsocketTransport
[javac] public void onOpen(ServerHandshake handshakedata) {
[javac] ^
[javac] /home/drhop/dev/otartc/third_party/socket.io-java-client/src/io/socket/WebsocketTransport.java:15: io.socket.WebsocketTransport is not abstract and does not override abstract method send(java.lang.String) in io.socket.IOTransport
[javac] class WebsocketTransport extends WebSocketClient implements IOTransport {
[javac] ^
[javac] /home/drhop/dev/otartc/third_party/socket.io-java-client/src/io/socket/WebsocketTransport.java:25: incompatible types
[javac] found : io.socket.WebsocketTransport
[javac] required: io.socket.IOTransport
[javac] return new WebsocketTransport(uri, connection);
[javac] ^
[javac] /home/drhop/dev/otartc/third_party/socket.io-java-client/src/io/socket/WebsocketTransport.java:33: cannot find symbol
[javac] symbol : class DefaultSSLWebSocketClientFactory
[javac] location: class io.socket.WebsocketTransport
[javac] this.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(context));
[javac] ^
[javac] /home/drhop/dev/otartc/third_party/socket.io-java-client/src/io/socket/WebsocketTransport.java:43: cannot find symbol
[javac] symbol : method close()
[javac] location: class io.socket.WebsocketTransport
[javac] this.close();
[javac] ^
[javac] /home/drhop/dev/otartc/third_party/socket.io-java-client/src/io/socket/WebsocketTransport.java:73: method does not override or implement a method from a supertype
[javac] @OverRide
[javac] ^
[javac] /home/drhop/dev/otartc/third_party/socket.io-java-client/src/io/socket/WebsocketTransport.java:79: method does not override or implement a method from a supertype
[javac] @OverRide
[javac] ^
[javac] /home/drhop/dev/otartc/third_party/socket.io-java-client/src/io/socket/WebsocketTransport.java:85: method does not override or implement a method from a supertype
[javac] @OverRide
[javac] ^
[javac] /home/drhop/dev/otartc/third_party/socket.io-java-client/src/io/socket/WebsocketTransport.java:96: method does not override or implement a method from a supertype
[javac] @OverRide
[javac] ^
[javac] 13 errors

Deadlock involving IOConnection instance and outputBuffer

I'm running into deadlocks every now and then. Taking a thread dump revealed the objects involved. A socket.io-java-client thread called "ConnectThread" calls IOConnection.connectTransport, which locks, in this order

  1. this (as connectTransport() is synchronized)
  2. outputBuffer (explicitly in IOConnection.transportConnected()

Now my own thread calls SocketIO.emit, which locks, in this order

  1. outputBuffer (explicitly in IOConnection.sendPlain())
  2. this (by calling getState() which is synchronized)

Still not having had the time to go read the code, the quick fix for me was to make IOConnection.sendPlain(String) synchronized, which reverses the order that sendPlain() takes those 2 locks, thus averting the deadlock.

It works great for me so far (I'm creating 5000 client instances in a single JVM in a matter of seconds now), but there might be better ways to fix it for those who know the code. In any event, here are the relevant bits from the thread dump (line numbers seem to be off by 1, and maybe by more due to my local changes, so it's probably easier to just use the method names).

Found one Java-level deadlock:

"Thread-5789":
waiting to lock monitor 0x00002aab9be10e48 (object 0x0000000785ebcde0, a java.util.concurrent.ConcurrentLinkedQueue),
which is held by "pool-1-thread-16"
"pool-1-thread-16":
waiting to lock monitor 0x00002aab9be07670 (object 0x0000000785ebcba0, a io.socket.IOConnection),
which is held by "ConnectThread"
"ConnectThread":
waiting to lock monitor 0x00002aab9be10e48 (object 0x0000000785ebcde0, a java.util.concurrent.ConcurrentLinkedQueue),
which is held by "pool-1-thread-16"

Java stack information for the threads listed above:

"Thread-5789":
at io.socket.IOConnection.sendPlain(IOConnection.java:449)
- waiting to lock <0x0000000785ebcde0> (a java.util.concurrent.ConcurrentLinkedQueue)
at io.socket.IOConnection.transportMessage(IOConnection.java:645)
at io.socket.WebsocketTransport.onMessage(WebsocketTransport.java:117)
at de.roderick.weberknecht.WebSocketReceiver.run(WebSocketReceiver.java:57)
"pool-1-thread-16":
at io.socket.IOConnection.getState(IOConnection.java:849)
- waiting to lock <0x0000000785ebcba0> (a io.socket.IOConnection)
at io.socket.IOConnection.sendPlain(IOConnection.java:450)
- locked <0x0000000785ebcde0> (a java.util.concurrent.ConcurrentLinkedQueue)
at io.socket.IOConnection.emit(IOConnection.java:826)
at io.socket.SocketIO.emit(SocketIO.java:236)
at benchmark.Benchmarker.RegisterInner(Benchmarker.java:215)
at benchmark.Benchmarker.access$100(Benchmarker.java:48)
at benchmark.Benchmarker$3.run(Benchmarker.java:204)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:206)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
"ConnectThread":
at io.socket.IOConnection.transportConnected(IOConnection.java:518)
- waiting to lock <0x0000000785ebcde0> (a java.util.concurrent.ConcurrentLinkedQueue)
at io.socket.WebsocketTransport.onOpen(WebsocketTransport.java:123)
at de.roderick.weberknecht.WebSocketConnection.connect(WebSocketConnection.java:139)
at io.socket.WebsocketTransport.connect(WebsocketTransport.java:129)
at io.socket.IOConnection.connectTransport(IOConnection.java:333)
- locked <0x0000000785ebcba0> (a io.socket.IOConnection)
at io.socket.IOConnection.access$200(IOConnection.java:38)
at io.socket.IOConnection$ConnectThread.run(IOConnection.java:200)

Found 1 deadlock.

Error on server restart

I started a socket.io server, then connected to it using a socket.io client, then I had to shut-down the server and start it again. The client showed the following cryptic exception:

io.socket.SocketIOException: 1+0
at io.socket.IOConnection.transportMessage(IOConnection.java:737)
at io.socket.WebsocketTransport.onMessage(WebsocketTransport.java:82)
at org.java_websocket.client.WebSocketClient.onWebsocketMessage(WebSocketClient.java:361)
at org.java_websocket.WebSocketImpl.deliverMessage(WebSocketImpl.java:565)
at org.java_websocket.WebSocketImpl.decodeFrames(WebSocketImpl.java:331)
at org.java_websocket.WebSocketImpl.decode(WebSocketImpl.java:152)
at org.java_websocket.client.WebSocketClient.interruptableRun(WebSocketClient.java:247)
at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:193)
at java.lang.Thread.run(Thread.java:722)
Exception in thread "Thread-16" java.lang.IllegalStateException: Timer already cancelled.
at java.util.Timer.sched(Timer.java:397)
at java.util.Timer.schedule(Timer.java:193)
at io.socket.IOConnection.reconnect(IOConnection.java:766)
at io.socket.IOConnection.transportDisconnected(IOConnection.java:559)
at io.socket.WebsocketTransport.onClose(WebsocketTransport.java:76)

no connection on cellular network

establishing a socket.io connection works beautifully in the android emulator and on devices with WiFi.
But it seems not to be able to connect when on HSPA. A least onConnect() is not called https://github.com/ANDLABS-Git/studio-lounge-droid/blob/master/src/eu/andlabs/studiolounge/gcp/GCPService.java#L59

Did anyone encounter similar issues?

Could this be a port / NAT / gateway issue with the mobile network operator? (O2 Germany in this case)
But the web/browser frontend http://happylog.jit.su is working on the exact same device with the exact same HSPA connection and the exact same socket.io backend :/ Could this be a fallback to a different transport in the browser?

Unterminated threads from wss connections

I have been experimenting with this library for a couple of months, and it seems to work well. Thanks to those who contributed. I wanted to share a fix to a problem where the JVM will not shut down properly because of lingering non-daemon threads.

After you connect to a SSL server using the websocket transport, you will see a thread named "pool-1-thread-1" appear. If you reconnect, or connect to a different server you'll see an additional "pool-2-thread-1" and so on.

These threads don't die and are non-daemon. I have tracked the problem down to the constructor call in org.java_websocket.client.DefaultSSLWebSocketClientFactory(SLContext sslContext), which calls "Executors.newSingleThreadScheduledExecutor()". The thread created by this function is not reused and never shut down.

Here's the fix I made to WebsocketTransport.java:

diff --git "a/C:\\Users\\WxPt\\AppData\\Local\\Temp\\WebF1AB.tmp\\WebsocketTransport-8f4c6b7-left.java" "b/C:\\ExternalLibs\\sources\\socket.io-java-client\\src\\io\\socket\\WebsocketTransport.java"
index 0ec9bee..df362dd 100644
--- "a/C:\\Users\\WxPt\\AppData\\Local\\Temp\\WebF1AB.tmp\\WebsocketTransport-8f4c6b7-left.java"
+++ "b/C:\\ExternalLibs\\sources\\socket.io-java-client\\src\\io\\socket\\WebsocketTransport.java"
@@ -3,6 +3,8 @@ package io.socket;
 import java.io.IOException;
 import java.net.URI;
 import java.net.URL;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
 import java.util.regex.Pattern;

 import javax.net.ssl.SSLContext;
@@ -16,6 +18,7 @@ class WebsocketTransport extends WebSocketClient implements IOTransport {
     private final static Pattern PATTERN_HTTP = Pattern.compile("^http");
     public static final String TRANSPORT_NAME = "websocket";
     private IOConnection connection;
+    private ExecutorService exec;
     public static IOTransport create(URL url, IOConnection connection) {
         URI uri = URI.create(
                 PATTERN_HTTP.matcher(url.toString()).replaceFirst("ws")
@@ -30,7 +33,8 @@ class WebsocketTransport extends WebSocketClient implements IOTransport {
         this.connection = connection;
         SSLContext context = IOConnection.getSslContext();
         if("wss".equals(uri.getScheme()) && context != null) {
-           this.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(context));
+           exec = Executors.newSingleThreadScheduledExecutor();
+           this.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(context, exec));
         }
     }

@@ -39,6 +43,10 @@ class WebsocketTransport extends WebSocketClient implements IOTransport {
      */
     @Override
     public void disconnect() {
+       if (exec != null) {
+           exec.shutdownNow();
+           exec = null;
+       }
         try {
             this.close();
         } catch (Exception e) {
@@ -98,4 +106,4 @@ class WebsocketTransport extends WebSocketClient implements IOTransport {
         // TODO Auto-generated method stub

     }
-}
\ No newline at end of file
+}

classnotfounderror

sock

I am doing a simple socket connection from android emulator. and it gives a classnotfound error for
websocketconnection

Refactor socket.io-java-client to reflect the socket.io/engine.io layers of the upcoming socket.io release.

Socket.io will be splitted into engine.io, a "lowlevel" TransportAPI and socket.io, bringing all features which come with socket.io.

socket.io-java-client has a similiar structure, but uses a more monolithic design, as IOConnection handles most of the work.

This library should be refactored to reflect these changes in socket.io. Logic belonging to socket.io rather than engine.io should move from IOConnection to SocketIO or a new class IOGlue, which glues both together. IOConnection should also renamed to EngineIO and be usable without SocketIO.

Not a bug report...

Greetings Gottox,

First, thank you! A Very well written implementation.

I've forked it to add some abilities possible through Gson inprogress

Then i had a thought: (to make it as declarative as the nodeside)

final PlanetInspection pi = new ThirdComing();

socket.when("enterprise:beams:recon", 

    Data.class, Spock.class, Kirk.class, BleepyThing.class

).then( new io.socket.IOEvent() {

        public void handle( Data data, Spock spock, Kirk kirk, BleepyThing nexus7 ) { 

            // 
            // possible >> ?
            // 

            pi.doWith( data, spock, kirk, nexus7 );

        }
    }
);

I'm not certain that is even possible... Or worth doing.

So i'm just putting it out there. (Here)

Caio

https connect

i'm trying to use your client for connect to https server. i'm calling method setDefaultSSLSocketFactory(getFactory()), but nothing happens - no connect, no errors, no warnings.
getFactory code:

public static SSLSocketFactory getFactory() throws Exception {
        KeyStore trusted = KeyStore.getInstance("BKS");
        InputStream in = context.getResources().openRawResource(R.raw.mystore);
        try {
            trusted.load(in, "pass".toCharArray());
        } catch (Exception e) {
            throw new AssertionError(e);
        } finally {
            in.close();
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(trusted);

        SSLContext ssl_context = SSLContext.getInstance("TLS");
        ssl_context.init(null, tmf.getTrustManagers(), null);

        return ssl_context.getSocketFactory();
    }

connect to server code:

try {
            socket = new SocketIO(context.getString(R.string.baseurl));
        } catch (MalformedURLException e1) {
            online = false;
            //e1.printStackTrace();
        }
        try {
            socket.setDefaultSSLSocketFactory(getFactory());
        } catch (Exception e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        socket.connect(new IOCallback() {
//...

tell me please what i'm doing wrong?

Socket.io closes transport for unknown reason

Output:

 info  - socket.io started
 debug - client authorized
 info  - handshake authorized 9379073361164362905
 debug - setting request GET /socket.io/1/websocket/9379073361164362905
 debug - set heartbeat interval for client 9379073361164362905
 debug - client authorized for 
 debug - websocket writing 1::
 debug - websocket writing 5:::{"name":"hello","args":["Hello, I am a socket and I have lived for 996 seconds"]}
 info  - transport end (undefined)
 debug - set close timeout for client 9379073361164362905
 debug - cleared close timeout for client 9379073361164362905
 debug - cleared heartbeat interval for client 9379073361164362905
 debug - discarding transport

Server:

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

io.sockets.on("connection", function(socket) {
    var Time = new Date();
    var timestamp=Time.getTime();
    setInterval(function () {
        var currentTime = new Date();
        var life=currentTime.getTime()-timestamp;
      socket.emit('hello', 'Hello, I am a socket and I have lived for '+life+' seconds');
    }, 1000);
});

Versions:

  • socket.io 0.9.5
  • node 0.6.11
  • HTC desire HD Android 2.3.5

Connecting with query parameters

Hi,

I had problems using your api when the url I needed to connect to had ?key=val

I am currently just trying to get a project working in my spare time so I have take your source into my project and fixed it. But my fix is pretty crude and might not working all cases.

The crux of the fix is in the handshake() method in IOConnection, to do something like this:

        URL origin = getOrigin();
        if (IOConnection.this.url.getQuery() != null && IOConnection.this.url.getQuery() != "") {
            url = new URL(origin.toString() + SOCKET_IO_1 + "?" + IOConnection.this.url.getQuery());
        } else {
            url = new URL(origin.toString() + SOCKET_IO_1);
        }

When you set the url field in IOConnection you only set the origin (there might be a good reason for this...!). Instead I changed it to set the full URL and then wrote a getOrigin method which I called in the right places.

private URL getOrigin() throws MalformedURLException {
    return new URL(IOConnection.this.url.getProtocol() + "://" + IOConnection.this.url.getHost());
}

This seems to work, apologies if I have misunderstood your api, thanks for writing it though :)

Rich

Java ME is not supported

Java ME is not supported! Java ME is not support variable-arity functions that is uses there (:

Possible leak in IOConnection.acknowledge HashMap

Hi,

We've spotted what we believe is a leak in IOConnection.acknowledge - acks are added to this HashMap, but they never seem to be removed. There's no call anywhere in the package to remove these, and external code outwith the package can't access the HashMap either.

Thanks,
Chris

Intermittent ConnectThread Exception

I intermittently encounter the following fatal exception after I connect to my server. I've attached the crash logs to help identify the issue. Is there something I'm doing incorrect here?

05-21 16:23:10.367: I/System.out(7412): Connection established
05-21 16:23:10.375: W/dalvikvm(7412): threadid=17: thread exiting with uncaught exception (group=0x4001e560)
05-21 16:23:10.375: E/AndroidRuntime(7412): FATAL EXCEPTION: ConnectThread
05-21 16:23:10.375: E/AndroidRuntime(7412): java.lang.IllegalStateException: TimerTask is canceled
05-21 16:23:10.375: E/AndroidRuntime(7412): at java.util.Timer.scheduleImpl(Timer.java:578)
05-21 16:23:10.375: E/AndroidRuntime(7412): at java.util.Timer.schedule(Timer.java:461)
05-21 16:23:10.375: E/AndroidRuntime(7412): at io.socket.IOConnection.resetTimeout(IOConnection.java:480)
05-21 16:23:10.375: E/AndroidRuntime(7412): at io.socket.IOConnection.transportConnected(IOConnection.java:515)
05-21 16:23:10.375: E/AndroidRuntime(7412): at io.socket.WebsocketTransport.onOpen(WebsocketTransport.java:123)
05-21 16:23:10.375: E/AndroidRuntime(7412): at de.roderick.weberknecht.WebSocketConnection.connect(WebSocketConnection.java:139)
05-21 16:23:10.375: E/AndroidRuntime(7412): at io.socket.WebsocketTransport.connect(WebsocketTransport.java:129)
05-21 16:23:10.375: E/AndroidRuntime(7412): at io.socket.IOConnection.connectTransport(IOConnection.java:332)
05-21 16:23:10.375: E/AndroidRuntime(7412): at io.socket.IOConnection.access$300(IOConnection.java:38)
05-21 16:23:10.375: E/AndroidRuntime(7412): at io.socket.IOConnection$ConnectThread.run(IOConnection.java:201)

Feature/documentation request: control the debug output

When I run the client, I get a lot of messages to stderr, such as:

Feb 12, 2013 3:25:28 PM io.socket.IOConnection transportMessage
INFO: < 5:::{"name":"status","args":[{"key":"remainingTime","value":"29:35"}]}

How can I suppress or control these messages?

Reconnecting behavior when socket.io server dies

When using this lib to connect to a socket.io server, and the server unexpectedly disconnects, there is no notification to the user of this behavior. Instead it reconnects (forever?) as found in this piece of relevant routine:

public void transportDisconnected() {
this.lastException = null;
setState(STATE_INTERRUPTED);
reconnect();
}

I understand that intermittent disconnects can be resolved using a few reconnects; but what if the server goes down for a long period of time? I would expect this behavior to be notified to the user of the lib, and he can take action afterwards. I've tried both javascript & obj-c implementations and they both seem to notify at least a disconnect event.

For now I'm calling onDisconnect() in this function instead of reconnect(), but I'm not sure this is the intended behavior. I suggest doing something like reconnecting periodically while sending disconnect events to the user.

Buffer messages when using namespaces

socket.send(socket.emit) doesn't cache messages when connecting to a url including a namespace.

SocketIO socket = new SocketIO("http://127.0.0.1:3001/namespace");
socket.connect(new IOCallback() {...});
// This line is ignored on a server.
socket.send("Hello Server!");

It's better to cache messages until a connection for a namespace is established.

isConnected() problem

When you create a new socket without connecting it,

this.socketIO = new SocketIO();

If you use, for example:

if (!this.socketIO.isConnected()) {
...
}

before connecting to anything, it will generate a null pointer exception.

It was easily tracked to the following method:

public boolean isConnected() {
return this.connection.isConnected();
}

Since the socket object was never connected to anything, the connection property is null.
A quick fix would be:

public boolean isConnected() {
return (null != this.connection) && (this.connection.isConnected());
}

That's what I'm using here. Let me know if you think there is a better way to solve it. Or even if it is supposed to behave like this...

Timer already cancelled

hello there
I've found this error log in my application

Socket encountered error
Error received: Timeout Error. No heartbeat from server within life time of the socket. closing.
Try reconnecting socket after 5000
Trying to connect to server
URL found: http://mydomain.com:80
Server will be http://mydomain.com:80
java.lang.IllegalStateException: Timer already cancelled.
  at java.util.Timer.sched(Timer.java:354)
  at java.util.Timer.schedule(Timer.java:170)
  at io.socket.IOConnection.reconnect(IOConnection.java:769)
  at io.socket.IOConnection.transportDisconnected(IOConnection.java:562)
  at io.socket.WebsocketTransport.onClose(WebsocketTransport.java:75)
  at org.java_websocket.client.WebSocketClient.onWebsocketClose(WebSocketClient.java:389)
  at org.java_websocket.WebSocketImpl.closeConnection(WebSocketImpl.java:412)
  at org.java_websocket.WebSocketImpl.closeConnection(WebSocketImpl.java:420)
  at org.java_websocket.WebSocketImpl.eot(WebSocketImpl.java:434)
  at org.java_websocket.client.WebSocketClient.interruptableRun(WebSocketClient.java:281)
  at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:204)
  at java.lang.Thread.run(Thread.java:680)
Error occurs Error while handshaking
io.socket.SocketIOException: Error while handshaking
  at io.socket.IOConnection.handshake(IOConnection.java:325)
  at io.socket.IOConnection.access$600(IOConnection.java:42)
  at io.socket.IOConnection$ConnectThread.run(IOConnection.java:202)
Caused by: java.net.UnknownHostException: mydomain.com
  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:195)
  at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
  at java.net.Socket.connect(Socket.java:529)
  at sun.net.NetworkClient.doConnect(NetworkClient.java:158) 
  at sun.net.www.http.HttpClient.openServer(HttpClient.java:388)
  at sun.net.www.http.HttpClient.openServer(HttpClient.java:523)
  at sun.net.www.http.HttpClient.<init>(HttpClient.java:227)
  at sun.net.www.http.HttpClient.New(HttpClient.java:300)
  at sun.net.www.http.HttpClient.New(HttpClient.java:317)
  at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:970)
  at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:911)
  at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:836)
  at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1172)
  at io.socket.IOConnection.handshake(IOConnection.java:316)
  ... 2 common frames omitted

I wonder, is it a goog idea to create a new Timer here https://github.com/Gottox/socket.io-java-client/blob/master/src/io/socket/IOConnection.java#L435

I mean, somenthing like this

backgroundTimer.cancel();
backgroundTimer = new Timer("backgroundTimer");

in order to avoid error while reconnecting?

Thanks

this issue could be related to #44

onConnect not called

Sometimes it happens that onConnect is never called even if the server received the WebSocket connection.
Then if I disconnect and I connect again usually it works.

Any hint?

I'm using Android 4.2

Reconnecting issue 7:::1+0

debug: set close timeout for client 438823659631090974
debug: cleared close timeout for client 438823659631090974
debug: cleared heartbeat interval for client 438823659631090974
debug: discarding transport
debug: setting request GET /socket.io/1/websocket/438823659631090974
debug: set heartbeat interval for client 438823659631090974
debug: websocket writing 7:::1+0
warn: client not handshaken client should reconnect
info: transport end (error)

To generate this launch node.js + socket.io. Connect a client (socket.io-java-client) to the server. Restart node.js (with socket.io ofc) and you will see the error.

Obviously there should be a way to detect when the websocket is writing 7:::1+0, and when it occurs the client should disconnect the socket and reconnect.

socket blocks on disconnect.

First of all thanks for this library.

I am trying to use it in one of my android app. I am having some issue with disconnection.

I am able to connect, emit and receive data, and sometimes successfully disconnect. But most time, the execution blocks on disconnect method call

mLiveSockIO.disconnect();

and onDisconnect() or onError() not getting called in this case, and app freezes. I debugged with breakpoint and I can confirm that execution blocks on above given line.

public void setupLiveSocketIO(){
    try {
        mLiveSockIO =   new SocketIO("http://" + mStreamHost + ":" +mStreamPort+"/");
    } catch (MalformedURLException e) {
        return;
    }

    mLiveSockIO.connect(new IOCallback() {
        @Override
        public void onMessage(JSONObject arg0, IOAcknowledge arg1) {
            AppConstants.log(mHostName + " On Message json " + arg0.toString()); 
        }

        @Override
        public void onMessage(String arg0, IOAcknowledge arg1) {
            AppConstants.log(mHostName + " On Message String " + arg0.toString());
        }

        @Override
        public void onError(SocketIOException arg0) {
            AppConstants.log("live sock io onError");
            arg0.printStackTrace();
        }

        @Override
        public void onDisconnect() {
            AppConstants.log(mHostName + "live sock io onDisconnect");
        }

        @Override
        public void onConnect() {
            AppConstants.log("live sock io on Connect");
            sendUpdatedLiveRequest("");
        }

        @Override
        public void on(final String arg0, IOAcknowledge arg1, Object... arg2) {
            for(int i = 0 ;i < arg2.length ;i++){
                final String response       =   arg2[i].toString();
                Thread thread               =   new Thread(new Runnable() {
                    @Override
                    public void run() {
                        JSONParser  parse   =   new JSONParser(response, mContext,arg0);
                        String result       =   parse.startParsing();
                        postNotificationString(AppConstants.PARSE_SUCCESSFULL, result, arg0);
                    }
                });
                thread.start();
            }
        }
    });
}

And my disconnect call

public void disconnect(){
    AppConstants.log(" disconnect called");
    if(mLiveSockIO != null && mLiveSockIO.isConnected()){
        mIsDisconnected                 =   true;
        mLiveSockIO.disconnect();
    }
    AppConstants.log(" socketio disconnected");
    clear();
    AppConstants.log(" dictionaries clear");
}

Well I am getting log

07-30 14:19:23.448: E/DEBUG(17969): disconnect called

and thats all.. Lines below

mLiveSockIO.disconnect()

never get executed. I am not getting any exception.. I am not sure what is causing this behaviour..

  1. I am connecting and disconnecting in the same thread (UI thread in this case). I somewhere read that is necessary
  2. There might be chance that, when the time disconnect gets called, there are data to be received on the socket. In my case , once disconnect is called I dont want to receive any pending data. But I couldn't find anyway to flush out the data before disconnecting.
  3. I am not using any synchronisation or lock mechanisms, that might cause such a block. There are no exception either.
  4. The server part is working fine.. A client code in iphone is connecting to the same server and getting disconnected successfully.

Default buffer size exceeded

08-17 08:50:53.156: I/global(318): Default buffer size used in BufferedWriter constructor. It would be better to be explicit if an 8k-char buffer is required.

It would be nice if we could specify buffer size somewhere, else larger data cant be transmitted.

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.