EzDevInfo.com

socket.io-java-client

Socket.IO Client Implementation in Java

Android: How to use Gottox/socket.io-java-client library with right way?

I have a service. I create a Thread for using socket.io-java-client library on separate thread in this Service.

I keep thread with following way:

@Override
public void run() {
    while (canLiveThread) {
    //  keep thread
    }
}

And this way fully wrong yes? To fix this solution I need find answer to following questions:

1. Are need to me create separately thread to use socket.io-java-client library in Service? Or I can use this library without thread, simply implement socket.io-java-client library in Service?

2. If need create thread to use this library, then how to manage thread with right way to not draining battery in background Service?

If anybody have any Solution, please answer to this question ...

Thanks in Advance!


Source: (StackOverflow)

connecting android client to sails.js

I'm using nkzawa socket.io android client. How can I connect it to sails.js server? I tried the approaches from Sending Socket request from Client (iOS & Android) to Sails.js Server and Simple Sails.js and Android Example but I get the following errors on my sails server:

Running "watch" task
Waiting...
verbose: A socket is being allowed to connect, but the session could not be loaded.  Will create an empty, one-time session to use for the life of the socket connection.  Details:
 Error: Session could not be loaded
    at _createError (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/lib/hooks/session/index.js:271:21)
    at Immediate._onImmediate (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/lib/hooks/session/index.js:274:13)
    at processImmediate [as _immediateCallback] (timers.js:358:17) { [Error: Session could not be loaded] code: 'E_SESSION' }
verbose: A socket is being allowed to connect, but the session could not be loaded.  Will create an empty, one-time session to use for the life of the socket connection.  Details:
 Error: Session could not be loaded
    at _createError (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/lib/hooks/session/index.js:271:21)
    at Immediate._onImmediate (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/lib/hooks/session/index.js:274:13)
    at processImmediate [as _immediateCallback] (timers.js:358:17) { [Error: Session could not be loaded] code: 'E_SESSION' }
verbose: Could not fetch session, since connecting socket has no cookie (is this a cross-origin socket?)
Generated a one-time-use cookie:sails.sid=s%3AZfXLqUZt5kQ4M0hPd-NI6-0AzciPjXDf.IjhbWcteKvKB9h5v0kcxYRis8Lo1JhpTHN9eTweXpdwand saved it on the socket handshake.
This will start this socket off with an empty session, i.e. (req.session === {})
That "anonymous" section will only last until the socket is disconnected unless you persist the session id in your database,
or by setting the set-cookie response header for an HTTP request that you *know* came from the same user (etc)
Alternatively, just make sure the socket sends a `cookie` header or query param when it initially connects.
verbose: Could not fetch session, since connecting socket has no cookie (is this a cross-origin socket?)
Generated a one-time-use cookie:sails.sid=s%3AFOsga3uhvU0N-CZsgAPAjY_IWZlGb5Cr.%2FjoQX1LkUU0OWeB1Kt3pr7cbFFOkMAirJ5ODPLwXgNAand saved it on the socket handshake.
This will start this socket off with an empty session, i.e. (req.session === {})
That "anonymous" section will only last until the socket is disconnected unless you persist the session id in your database,
or by setting the set-cookie response header for an HTTP request that you *know* came from the same user (etc)
Alternatively, just make sure the socket sends a `cookie` header or query param when it initially connects.
verbose: Receiving incoming message from Socket.io:  [ { url: '/user/new' } ]
error: Error (SAILS:HOOK:SOCKETS:PARSE_VIRTUAL_REQ):: Failed to parse incoming socket.io request.
    at new constructor (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/standalone/create-error-constructor.js:38:16)
    at Errorpack.factory [as PARSE_VIRTUAL_REQ] (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/standalone/create-error-factory.js:34:12)
    at respondWithParseError (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/lib/receive-incoming-sails-io-msg.js:247:29)
    at receiveIncomingSailsIOMsg (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/lib/receive-incoming-sails-io-msg.js:41:14)
    at Socket.<anonymous> (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/lib/on-connect.js:84:9)
    at Socket.emit (events.js:107:17)
    at Socket.onevent (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/lib/socket.js:330:8)
    at Socket.onpacket (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/lib/socket.js:290:12)
    at Client.ondecoded (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/lib/client.js:193:14)
    at Decoder.Emitter.emit (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/node_modules/socket.io-parser/node_modules/component-emitter/index.js:134:20)
    at Decoder.add (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/node_modules/socket.io-parser/index.js:247:12)
    at Client.ondata (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/lib/client.js:175:18)
    at Socket.emit (events.js:107:17)
    at Socket.onPacket (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/node_modules/engine.io/lib/socket.js:99:14)
    at WebSocket.emit (events.js:129:20)
    at WebSocket.Transport.onPacket (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/node_modules/engine.io/lib/transport.js:91:8) { [Error (SAILS:HOOK:SOCKETS:PARSE_VIRTUAL_REQ):: Failed to parse incoming socket.io request.]
  code: 'SAILS:HOOK:SOCKETS:PARSE_VIRTUAL_REQ',
  name: 'Error (SAILS:HOOK:SOCKETS:PARSE_VIRTUAL_REQ):',
  status: 400,
  message: 'Failed to parse incoming socket.io request.',
  stack: 'Error (SAILS:HOOK:SOCKETS:PARSE_VIRTUAL_REQ):: Failed to parse incoming socket.io request.\n    at new constructor (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/standalone/create-error-constructor.js:38:16)\n    at Errorpack.factory [as PARSE_VIRTUAL_REQ] (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/standalone/create-error-factory.js:34:12)\n    at respondWithParseError (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/lib/receive-incoming-sails-io-msg.js:247:29)\n    at receiveIncomingSailsIOMsg (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/lib/receive-incoming-sails-io-msg.js:41:14)\n    at Socket.<anonymous> (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/lib/on-connect.js:84:9)\n    at Socket.emit (events.js:107:17)\n    at Socket.onevent (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/lib/socket.js:330:8)\n    at Socket.onpacket (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/lib/socket.js:290:12)\n    at Client.ondecoded (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/lib/client.js:193:14)\n    at Decoder.Emitter.emit (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/node_modules/socket.io-parser/node_modules/component-emitter/index.js:134:20)\n    at Decoder.add (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/node_modules/socket.io-parser/index.js:247:12)\n    at Client.ondata (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/lib/client.js:175:18)\n    at Socket.emit (events.js:107:17)\n    at Socket.onPacket (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/node_modules/engine.io/lib/socket.js:99:14)\n    at WebSocket.emit (events.js:129:20)\n    at WebSocket.Transport.onPacket (/usr/local/node-v0.12.4-linux-x64/lib/node_modules/sails/node_modules/sails-hook-sockets/node_modules/socket.io/node_modules/engine.io/lib/transport.js:91:8)',
  details: 'No url provided in request: [object Object]' }

This is my android client:

JSONArray arr = new JSONArray();
JSONObject obj = new JSONObject();
try {
    obj.put("url", "/user/new");
} catch (JSONException e) {
    e.printStackTrace();
}
arr.put(obj);
socket.emit("get", arr);

Source: (StackOverflow)

Advertisements

socket.io xhr post error on slow connection (3G mobile network)

While I am testing my real chat application on 3G mobile network (Slow internet connection), Socket.io repeatedly disconnects then reconnects. I have logged the reason. it says "xhr post error" which raise "transport error" then disconnect.

May I know what is the meaning of "xhr post error" and why this error appears in slow connection and how to solve the problem?.

I am using socket.io-client.java version 0.4.2


Source: (StackOverflow)

Android socket.io client

I'm trying to set up a android socket.io client, but I'm having some difficulties. Right now I'm using this library:https://github.com/nkzawa/socket.io-client.java and everything is working great when we turn off the middleware. When it's turned on I need to send a header while connecting to the server but as I understand this library doesn't provide such possibility. So can someone propose a different library or share a workaround for this issue?

Thanks


Source: (StackOverflow)

Can a Socket.io Server with an Emitter be setup without a Redis server?

I got a Socket.io Server running with a Redis server. And there's a Java application that emits events to the Redis server for it to be received by Socket.io clients.

In a development environment, is it possible to run this without using a Redis server? Or are there any very lightweight Redis server implementations preferably in NodeJS that exist?

At the moment I'm using Vagrant with a box that already got Redis installed, but I'd rather not as it requires all developers to install Virtual Box + Vagrant.

Thank you.


Source: (StackOverflow)

Socket.IO heartbeat not sent

I've been running a Socket.IO server (https://github.com/mrniko/netty-socketio) , communicating with a client (https://github.com/nkzawa/socket.io-client.java) that runs on an Android emulator. The emulator is hosted on the machine that runs the server. I was able to create the initial connection from the client to the server, and successfully send a message (client to server), but shortly after that the heartbeat failed and the connection was broken:

DEBUG [07:17:45.470] c.c.socketio.transport.NamespaceClient: Client 157e4f73-e26d-459c-ac1c-506628b66a09 for namespace has been disconnected DEBUG [07:17:45.470] c.c.socketio.SocketIOChannelInitializer: Client with sessionId: 157e4f73-e26d-459c-ac1c-506628b66a09 disconnected DEBUG [07:17:45.470] c.c.socketio.transport.NamespaceClient: Client 157e4f73-e26d-459c-ac1c-506628b66a09 for namespace /android/ has been disconnected DEBUG [07:17:45.471]
c.c.socketio.handler.ClientHead: 157e4f73-e26d-459c-ac1c-506628b66a09 removed due to ping timeout DEBUG [07:17:46.119]
c.c.s.transport.WebSocketTransport: Client with was already disconnected. Channel closed!

Server code:

Configuration serverConfig = new Configuration();
serverConfig.setHostname(MACHINE_IP);
serverConfig.setPort(8082);
serverConfig.setPingTimeout(20);
SocketIOServer server = new SocketIOServer(serverConfig);
server.addNamespace("/android/")
server.start()

Client code:

IO.Options options = new IO.Options();
options.transports = new String[]{"websocket"};
options.reconnectionAttempts = 5;
options.reconnectionDelay = 10000;
Socket socket = IO.socket(MACHINE_IP + ":8082/android/", options)

What am I doing wrong? Thanks.


Source: (StackOverflow)

(Android) Hold a Socket.IO Connection throughout Activities

I'm basically trying to start a Socket.IO connection in one activity (The LogIn Activity) and carry that throughout the various other activities. If anyone has any idea on what would work the best in this situation that would be great. All I need is probably a service that I can run in the background but I haven't been able to figure out how that works. I tried doing this but that doesn't work.

public class KlassAttack extends Application {
    Socket gameConnection;
    @Override
    public void onCreate() {
        try {gameConnection = IO.socket("http://71.13.36.124:56543");}catch(URISyntaxException e){}
        gameConnection.connect();
        Log.e("TEST", "EEE");
    }
}

Source: (StackOverflow)

How to use callback on a socket.io CLIENT?

I want to callback the server to ack that my client has received a call. In the opposite direction, this is heavily documented and working fine, but how can I ack from the client?

NB: I am using socket-io-java-client https://github.com/socketio/socket.io-client-java on Android, not JavaScript, but it shouldn't matter. Well, maybe it does.

    socket.on("onMessage", new Emitter.Listener() {
                @Override public void call(Object... args) {
                    // I have the args here and the last argument is a callback,
                    // but what do I need to do to callback the server using that arg?
                }
            })

In Swift it looks like this, but I can't figure out how to do this in Java with the above mentioned library.

    socket.on("onMessage") { data, ack in
        ack?()
    }

Has anybody done this or knows how to achieve that?


Source: (StackOverflow)

Boolean not updated before onPostExecute runs

I have a problem with returning the result value to onPostExecute() of an onBackground() function in the Async Class of Android.

What I want to do is to search for a specified contact name in a database using socket.io and then when I find it; return true to onPostExecute so that I can do something there when the contact has been found. If nothing has been found, false shall be returned and something else should be done in onPostExecute(). I set the boolean global value "success" to true or false respectively and try to pass this value to onPostExecute(), but for some reason the value is assigned AFTER onPostExecute() is called ... must have something to do with asynchronous operation, but since I am not an expert, I hope someone can give me some hint on how to do it right so that the boolean value is updated, BEFORE onPostExecute() checks the value.

This is my code:

public class AsynchronicTask extends AsyncTask<Object, Void, Boolean> {

SocketIO socket = null;
AsyncObject asyncObject = null;
Boolean success = false;

@Override
protected Boolean doInBackground(final Object... argument) {
    this.asyncObject = (AsyncObject) argument[0];

    try {
        System.out.println("Trying to connect to: "
                + asyncObject.getURL());
        socket = new SocketIO(asyncObject.getURL());
        socket.connect(new IOCallback() {

            @Override
            public void onConnect() {
                JSONObject queriedUsername = new JSONObject();
                try {
                    queriedUsername.put("Username", asyncObject.getQueryInput());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                socket.emit("clientRequestSearchUsername", queriedUsername);
            }

            @Override
            public void onDisconnect() {
            }

            @Override
            public void onError(SocketIOException arg0) {
            }

            @Override
            public void onMessage(String arg0, IOAcknowledge arg1) {
            }

            @Override
            public void onMessage(JSONObject arg0, IOAcknowledge arg1) {
            }

            @Override
            public void on(final String message, IOAcknowledge argIO,
                    final Object ... arg) {
                if (message.equals(asyncObject.getServerMessage())) {
                    if (arg[0].equals("null")) {
                        Log.e("ERROR", "No Result Found");
                        success = false;
                    } else {
                        success = true;
                        Log.d("DEBUG", "RESULT OK!");
                    }
                };
            }
        });

    } catch (MalformedURLException e) {
        Log.e("error", "Wrong Server URL");
        e.printStackTrace();
    }

return success;
}

@Override
protected void onPostExecute(Boolean result) {
    Log.d("DEBUG", result.toString());

    // Give reply when username query has finished
     if (result.equals(true)){
     Log.d("DEBUG", "Contact found, adding to contactlist");
     // Populate data in contactViewAdapter
     asyncObject.getContactListAdapter().populateAdapter(asyncObject.getQueryInput());
     Toast.makeText(asyncObject.getContext(), "Contact added", Toast.LENGTH_SHORT).show();
     } 
     else { 
         Log.d("DEBUG", "No Success adding contact, no contact found");
         Toast.makeText(asyncObject.getContext(), "Username not existent, no contact added", Toast.LENGTH_SHORT).show(); 
     }  
 }
 }

Source: (StackOverflow)

Accessing a socket.io earlier version?

There's a Socket.IO service that's running the 0.9 protocol. They have plans to upgrade, but the timing is outside my influence and unpredictable. I want to use the service today, preferably from the JVM.

The docs for the Socket.IO libraries suggest that 0.9 to 1.0 is a breaking change and make no attempt at backward compatibility. There is no version of the Java client library for 0.9.

Is there any hope of using an official library to talk to the 0.9 service? Some kind of version-translating proxy?


Source: (StackOverflow)

java.net.SocketException: Connection reset With HTTPConnection

I am trying to hit some external API to fetch some data. When the data size is small, everything works fine but when the size of data returned by the API is big I get CONNECTION RESET exception. The below code is from java class InterfaceHelper and I have also marked the comment at the line no where I am getting exception [Its while trying to read data from InputStream].

I have tried to search so many question on STACKOVERFLOW itself but didn't find an appropriate answer. So please don't mark it as duplicate question. I want to know what is the reason behind this problem, and what is the proper solution for this problem. If you find this question as duplicate please answer it before marking it as duplicate. I dare you.

Find below my code which I have used. URL is some dummy url as for security reason I cannot mention the actual URL I have used.

 try{
        URL url = new URL("http://example.com/someParams/SOME-ACCESS-TOKEN");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setRequestProperty("X-EXAMPLE-LOGIN", "XXXXXXXX");
        connection.setRequestProperty("X-EXAMPLE-PASSWORD", "XXXXXX");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        DataInputStream input = new DataInputStream(connection.getInputStream());
        String  ret = "";
        if(input!=null){
            for( int c = input.read(); c != -1; c = input.read() ) { //InterfaceHelper.java:695
                ret = ret + String.valueOf((char)c);
            }
        }

         if(input!=null)
             input.close();
         if(connection!=null)
             connection.disconnect();

                if(ret!=null && ret.length()>0){
                    return ret;
                }

    }catch(Exception e) {
        e.printStackTrace();
    } 

This the exception I get

        java.net.SocketException: Connection reset
        at java.net.SocketInputStream.read(SocketInputStream.java:196)
        at java.net.SocketInputStream.read(SocketInputStream.java:122)
        at sun.security.ssl.InputRecord.readFully(InputRecord.java:442)
        at sun.security.ssl.InputRecord.readV3Record(InputRecord.java:554)
        at sun.security.ssl.InputRecord.read(InputRecord.java:509)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
        at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:884)
        at sun.security.ssl.AppInputStream.read(AppInputStream.java:102)
        at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
        at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
        at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
        at sun.net.www.http.ChunkedInputStream.fastRead(ChunkedInputStream.java:244)
        at sun.net.www.http.ChunkedInputStream.read(ChunkedInputStream.java:689)
        at java.io.FilterInputStream.read(FilterInputStream.java:133)
        at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3053)
        at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3047)
        at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3035)
        at java.io.FilterInputStream.read(FilterInputStream.java:83)
        at com.lsa.akosha.util.InterfaceHelper.hitApiBrandWatch(InterfaceHelper.java:695)
        at com.lsa.akosha.service.brand.BrandCronService.brandSentiments(BrandCronService.java:288)
        at com.lsa.akosha.util.thread.BrandWatchCronConverse.executeInternal(BrandWatchCronConverse.java:60)
        at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:113)
        at org.quartz.core.JobRunShell.run(JobRunShell.java:213)
        at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557)

Source: (StackOverflow)

Error running Gottox/socket.io-java-client

Hi So i am trying to run the socket.io-java-client from Gottox and simple by just opening the project in eclips(import) AND running BasicExample.java i am getting this error

Error while handshaking Server returned HTTP response code: 400 for URL: http://localhost:3000/socket.io/1/

I tried many solution but was not able to run it, also i am running the nodejs server on port 3000.

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
res.sendfile('index.html');
});

io.on('connection', function(socket){
console.log('a user connected');

socket.on('message', function(msg){
io.emit('message', msg);
console.log('1111111111111111111');
});
});

http.listen(3000, function(){
console.log('listening on *:3000');
});

Source: (StackOverflow)

socket.io Android library authentification

I use this library (https://github.com/socketio/socket.io-client-java) to connect my Android application with my Sails socket.io.

Here is the code I use :

final Socket socket = IO.socket(Constants.LOCAL_URL+"?__sails_io_sdk_version=0.11.0");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener()
            {

                @Override
                public void call(Object... args)
                {
                    JSONObject obj1 = new JSONObject();
                    try {
                        obj1.put("url","/rest/room");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    socket.emit("get", obj1, new Ack() {
                        @Override
                        public void call(Object... args) {
                            Log.e("test", "GET");
                        }
                    });
                    Log.e("test", "CONNECT");
                }

            }).on("room", new Emitter.Listener()
            {
                @Override
                public void call(Object... args)
                {

                    Log.e("test", "ROOM");
                }
            });

But I have a 403 cause URL need an authentification. So how can I modify socket headers to put the Cookie and keep the session between sockets and web services ?


Source: (StackOverflow)