GithubHelp home page GithubHelp logo

socket.io-android-chat's Introduction

socket.io-android-chat

This is a simple chat demo for socket.io and Android. You can connect to https://socket-io-chat.now.sh using this app.

Installation

  1. Clone the project.
  2. In Android Studio, chose File > Import Project and select the root folder of the project. Android Studio may ask you to choose the type of project you are importing. If this is the case, make sure to choose Import project from external model and select the Gradle option.

Tutorial

http://socket.io/blog/native-socket-io-and-android/

Misc

socketio/socket.io#2823

License

MIT

socket.io-android-chat's People

Contributors

bongjaechoi avatar live-wire avatar nkzawa avatar sanchitgarg1909 avatar yashade 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-android-chat's Issues

How to specify timeout?

I'm getting (Socket.EVENT_CONNECT_TIMEOUT after a minute and a half after my Internet connection was closed. How to reduce timeout?

Primus

Can this be used on Primus?

Problem with connecting to NodeJS server

For my NodeJS server code, I'm using the chat server code that is linked to in the socket io android tutorial.

I'm following the tutorial above to a tee in my android project.

build.gradle:

...
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.github.nkzawa:socket.io-client:0.3.0'
}

AndroidManifest.xml:

...
<uses-permission android:name="android.permission.INTERNET" />
...

MainActivity.java:

import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;

public class MainActivity extends AppCompatActivity {

    private Socket mSocket;
    {
        try {
            mSocket = IO.socket("http://chatserver:3000");
            Log.e("CONNECTED", "SUCCESS");
        } catch (URISyntaxException e) {
            Log.e("ERROR", "ERROR CONNECTING");
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSocket.connect();
        mSocket.emit("message", "message");
    }
}

When I compile this, no matter what I put as the URL for IO.socket(<url>), it always logs out that it connected. When I load the app, it's supposed to emit message and send "message", but I never get it on the server. I never even get a "user connected" log in my server log, which I have setup to log out anytime a something connects to it.

Just to test to make sure my server code isn't faulty, I created a client project in NodeJS:

client.js:

var io = require('socket.io-client'),
socket = io.connect('http://localhost:3000');

socket.on('connect', function(){
  console.log("connected")
});

And it and the server both log out 'connected' when I run it. So something is wrong with the java code.... I can't figure it out.

Not find class okhttp3.OkHttpClient$Builder

Hi i tried add the .jar's, i tried add older libreries and only in one of my disp for bug this error out.

E/dalvikvm: Could not find class 'okhttp3.OkHttpClient$Builder', referenced from method io.socket.engineio.client.transports.WebSocket.doOpen
05-17 17:37:06.707 30194-31321/mx.com.avanceytec.ventascampo E/AndroidRuntime: FATAL EXCEPTION: EventThread
Process: mx.com.avanceytec.ventascampo, PID: 30194
java.lang.NoClassDefFoundError: okhttp3.OkHttpClient$Builder

this are my dependencies:
_dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile('org.apache.httpcomponents:httpclient-android:4.3.5.1') {
exclude module: 'com.squareup.okio'
}
compile('io.socket:socket.io-client:0.7.0') {
// excluding org.json which is provided by Android
exclude group: 'org.json', module: 'json'
}
compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.android.support:design:23.2.0'
compile 'com.android.support:support-v4:23.2.0'
compile 'com.loopj.android:android-async-http:1.4.7'
compile 'com.google.android.gms:play-services-location:8.4.0'
compile 'com.android.support:cardview-v7:23.2.0'
compile 'com.android.support:recyclerview-v7:23.2.0'
compile 'com.google.android.gms:play-services:8.4.0'
//compile 'com.github.gcacace:signature-pad:1.1.0'

}_
Help me please. Thanks

Timout Issue

Not getting timeout event some times in call() Emitter.Listener. but its coming in Manager open() method in timeout

if (Manager.this._timeout >= 0) {
                    final long timeout = Manager.this._timeout;
                    logger.fine(String.format("connection attempt will timeout after %d", timeout));

                    final Future timer = getTimeoutScheduler().schedule(new Runnable() {
                        @Override
                        public void run() {
                            EventThread.exec(new Runnable() {
                                @Override
                                public void run() {
                                    logger.fine(String.format("connect attempt timed out after %d", timeout));
                                    openSub.destroy();
                                    socket.close();
                                    socket.emit(Engine.EVENT_ERROR, new SocketIOException("timeout"));
                                    self.emitAll(EVENT_CONNECT_TIMEOUT, timeout);
                                }
                            });
                        }
                    }, timeout, TimeUnit.MILLISECONDS);

                    Manager.this.subs.add(new On.Handle() {
                        @Override
                        public void destroy() {
                            timer.cancel(false);
                        }
                    });
                }

Socket disconnected on close application(Fixed)

Hi i'm trying to keep my application's service on background. But on close application. Connected socket not work. I dont have any close that on application normally and i'm using service instead intent service and using STICKY on start cimmand too. What hapen when i close app.socket dosconnected? Is there any solution to keep alive socket or service?

This has a conflict with okhttp dispatcher (retrofit)

I tried to connect using this library and I'm also using okhttp for some api request but it has a conflict with okhttp dispatcher.

03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: java.lang.NoSuchMethodError: com.squareup.okhttp.internal.Internal.callEngineGetConnection
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at com.squareup.okhttp.ws.WebSocketCall.createWebSocket(WebSocketCall.java:154)
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at com.squareup.okhttp.ws.WebSocketCall.access$000(WebSocketCall.java:42)
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at com.squareup.okhttp.ws.WebSocketCall$1.onResponse(WebSocketCall.java:102)
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:177)
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)

high memory usage

Hello
the application memory usage is about 5 megabytes
I want to use it for push purposes
is it possible to reduce memory usage ?

Always getting Connect_error

Hi,

I downloaded you source code and changed the CHAT_SERVER_URL to my localhost nodejs socket io instance and its always throwing error Connect_error. I tried with connecting to my localhost server using the plain html for testing purpose and it worked without any issues. Could you please check where I'm doing wrong?

server code: v.1.3.6

// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;

var io = require('socket.io')(server);
io.on('connection', function (socket) {
  var addedUser = false;
  console.log("connected");

  // when the client emits 'new message', this listens and executes
  socket.on('new message', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });

    console.log(data);
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    // we store the username in the socket session for this client
    socket.username = username;
    // add the client's username to the global list
    usernames[username] = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', function () {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', function () {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    // remove the username from global usernames list
    if (addedUser) {
      delete usernames[socket.username];
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });

});

My test index.html file -

            <script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
            <script type="text/javascript">
             var socket = io.connect('http://localhost:9000');
            //socket.connect();
           socket.on('connect', function() {
                     console.log('connected');
             });


              socket.emit("new message", "Test message from client");       

          </script>

Android create single service instance

Hi all. in my application i cant create simple single service to connect to Socket, in my application after first run application i can emmit one request, but after close application and run again, my app send twice request to socket.io, and after clear app from recent application, that send multiple request to socket.io. please help me to create single service to create one connection, Thanks

My Service:

public class SignalChatServiceProvider extends Service {
    public static      SignalChatServiceProvider instance                    = null;

    public static boolean isInstanceCreated() {
        return instance == null ? false : true;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }

    private final IBinder myBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        public SignalChatServiceProvider getService() {
            return SignalChatServiceProvider.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        realm = Realm.getDefaultInstance();
        signalApplication = (SignalApplication) getApplication();
        EventBus.getDefault().register(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        connectConnection();
        Log.e("EJRA...", "");
        return START_STICKY;
    }


    private Runnable onTypingTimeout = new Runnable() {
        @Override
        public void run() {

        }
    };

    private void connectConnection() {

        instance = this;
        signalApplication.CHAT_SOCKET = signalApplication.getSocket();
        signalApplication.getSocket().on(Socket.EVENT_CONNECT_ERROR, onConnectError);
        signalApplication.getSocket().on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
        signalApplication.getSocket().on(Socket.EVENT_CONNECT, onConnect);

        signalApplication.getSocket().on("new message", onNewMessage);
        signalApplication.getSocket().on("user joined", onUserJoined);
        signalApplication.getSocket().on("getProductImages", getProductImages);

        signalApplication.getSocket().connect();
    }

    private void disconnectConnection() {
        instance = null;

        signalApplication.getSocket().disconnect();

        signalApplication.getSocket().off(Socket.EVENT_CONNECT, onConnect);
        signalApplication.getSocket().off(Socket.EVENT_DISCONNECT, onDisconnect);
        signalApplication.getSocket().off(Socket.EVENT_CONNECT_ERROR, onConnectError);
        signalApplication.getSocket().off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
        signalApplication.getSocket().off("new message", onNewMessage);
        signalApplication.getSocket().off("user joined", onUserJoined);
        signalApplication.getSocket().off("getProductImages", getProductImages);

        signalApplication.getSocket().disconnect();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        disconnectConnection();

        if (!realm.isClosed())
            realm.close();
    }
}

ActivityMain:

    if (signalApplication.getSocket() != null && !SignalChatServiceProvider.isInstanceCreated()) {
        startService(new Intent(getBaseContext(), SignalChatServiceProvider.class));
    }

Application class:

public class SignalApplication extends Application {

    public static List<MarketsBaseInformation> market_list_cache_data;
    public static Socket                       CHAT_SOCKET;

    @Override
    public void onCreate() {
        super.onCreate();

        resources = this.getResources();
        context = getApplicationContext();

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

        try {
            CHAT_SOCKET = IO.socket(ClientSettings.getChatAddress(), opts);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            Log.e("SOCKET.IO ", e.getMessage());
        }


    }

    public Socket getSocket() {
        return CHAT_SOCKET;
    }
}

I have a problem about session.

my server use express4 and socket.io. use express when account login, register and so on. if user login success then this account use socket.io client login the chat....
but, I find the same client's session on server has two session id, one express, on socket.io.
android client use httpclient connect to express api. that socketcleint connect to socket.io.
so...sockectClient dosen't set cookie. I don't know to resolve!

Ack after .on listener

Can I send back Ack to server after I have received an event from the server?!

Thanks.

Cannot move on from Login Activity

I've implemented a port of this Lib into my Android app, and I can't seem to move to the chat fragment when I input a nickname.. Not sure if it's because it's not declared as MAIN in my Androidmanifest.xml file or what... But can someone please point me to the right direction... Thanks...

Can not setup port with IO.Options

Hello,

I can't setup port with IO.Options in Android, When socket.connect(), it always connect to port 80,

try to add port in host url > "http://host : port", but useless, and i use example both Node.js server

and Android, Node.js can get port 3000, Android's socket.connect() can't...

Could someone know this issue ? many thanks!!

Issue in Socket.io android

Sir I have an issue listen socket from server . You make for group chat but I want one-one lisntening from server or you can say private chat only one person chat to other person please tell me how do I manage this

Does it support namespace?

Hi nkzawa,
May I know if this lib support namespace ?
Need to integration with nodejs server, Automattic/socket.io.
Thanks.

Custom socket id from android side

In the android library, socket.id() returns the id of the socket, however, there is no method (that I found in the jar file) that lets us set the socket id.

How can I set the socket id for my communication. In the nodejs sample, setting socket.id = "customName" works allowing us to decide our own name space for the sockets. Is there such an implementation in android?

I am developing a chat app wherein I want the socket.id() of the users to be their username itself. So irrespective of when they connect, instead of getting a random id, it is fixed to their username. I plan to set the id as soon as a connection is made.

In Nodejs my code is following -

io.on('connection', (socket)=>{
  console.log('new connection received');
  console.log(socket.id)
  socket.id = "username"
  console.log(socket.id)

  //other methods
}

This changes the socket id, but io.to(id).emit('new_message', data) does not work. If i use the random id generated, then this method is working just fine.

Please advise.

Cannot connect to the scoket io server

This is my server

var app = require('http').createServer()
var io = require('socket.io')(app);
var fs = require('fs');

var init = function(port){
    app.listen(port);
}

io.on('connection', function(socket){
    console.log('connected');
    socket.on('room_request', function(msg){
        console.log(msg);
        //room_index = msg;

        for( i = 0; i < msg.length; i++)
        {   
            socket.join(msg[i]);
            console.log('channel created');
        }
        socket.on('disconnect', function(){
            for( i = 0; i < msg.length; i++)
            {   
                console.log('user disconnected');
                socket.leave(msg[i]);
                console.log('room closed');
            }
        });
    });
});



var sendMessage = function(tId,message){
    io.to(tId).emit('ping',message);
}

exports.sendMessage = sendMessage;
exports.init = init;

The init is called from another file.
The server works because I tried connecting to it from a simple html javascript app.

I downloaded the app and replaced the http://chat.socket.io with 'localhost:8089'(Thats the port on which the server is running).
I ran it on the simulator so the localhost would resolve to the same machine. But still the server is not hit.
Anything wrong that I am doing anywhere?

Socket Disconnect if (android) app is in background and multiple app opens

Hi,

We developed a chat application for android using socket.io library, But we are facing one issue.

When we kept app in background socket remains connected, even if we keep it idle for some time, socket doesn't disconnect which is fine, but the problem comes when we open any other app, socket disconnects.

Can you please tell us what can be the problem & solution for that.

Thanks in advance...

Unable to run after adding gradle dependency for Android Studio, in build.gradle

BUILD SUCCESSFUL upon adding on dependencies

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'org.apache.commons:commons-lang3:3.1'
compile 'org.apache.commons:commons-collections4:4.0'
compile 'com.google.android.gms:play-services:6.1.+'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3'
compile 'com.facebook.android:facebook-android-sdk:3.23.1'
compile 'com.github.manuelpeinado.fadingactionbar:fadingactionbar:3.1.2'
compile 'com.android.support:cardview-v7:21.0.+'
compile 'com.android.support:recyclerview-v7:+'
compile 'com.etsy.android.grid:library:1.0.5'
compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
compile 'com.melnykov:floatingactionbutton:1.3.0'
compile('org.apache.httpcomponents:httpmime:4.3.6') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
compile('com.twitter.sdk.android:twitter:1.8.0@aar') {
transitive = true;
}
compile('com.crashlytics.sdk.android:crashlytics:2.5.2@aar') {
transitive = true;
}

compile 'io.socket:socket.io-client:0.6.1'

}


After I Run the app.I get this error...


Executing tasks: [:app:assembleDebug]

Configuration on demand is an incubating feature.
WARNING: Dependency org.json:json:20090211 is ignored for debug 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
WARNING: Dependency org.json:json:20090211 is ignored for debug 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
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
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
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72103Library UP-TO-DATE
:app:prepareComAndroidSupportCardviewV72103Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72301Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42301Library UP-TO-DATE
:app:prepareComAstuetzPagerslidingtabstrip101Library UP-TO-DATE
:app:prepareComCrashlyticsSdkAndroidAnswers132Library UP-TO-DATE
:app:prepareComCrashlyticsSdkAndroidBeta113Library UP-TO-DATE
:app:prepareComCrashlyticsSdkAndroidCrashlytics252Library UP-TO-DATE
:app:prepareComCrashlyticsSdkAndroidCrashlyticsCore235Library UP-TO-DATE
:app:prepareComDigitsSdkAndroidDigits180Library UP-TO-DATE
:app:prepareComEtsyAndroidGridLibrary105Library UP-TO-DATE
:app:prepareComFacebookAndroidFacebookAndroidSdk3231Library UP-TO-DATE
:app:prepareComGithubManuelpeinadoFadingactionbarFadingactionbar312Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServices6171Library UP-TO-DATE
:app:prepareComMelnykovFloatingactionbutton130Library UP-TO-DATE
:app:prepareComTwitterSdkAndroidTweetComposer090Library UP-TO-DATE
:app:prepareComTwitterSdkAndroidTweetUi150Library UP-TO-DATE
:app:prepareComTwitterSdkAndroidTwitter180Library UP-TO-DATE
:app:prepareComTwitterSdkAndroidTwitterCore150Library UP-TO-DATE
:app:prepareIoFabricSdkAndroidFabric136Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:processDebugManifest UP-TO-DATE
:app:fabricGenerateResourcesDebug
:app:processDebugResources
:app:generateDebugSources
:app:processDebugJavaRes UP-TO-DATE
:app:compileDebugJavaWithJavac
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources
:app:preDexDebug
:app:dexDebug
AGPBI: {"kind":"simple","text":"UNEXPECTED TOP-LEVEL EXCEPTION:","sources":[{}]}
AGPBI: {"kind":"simple","text":"com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.merge.DexMerger$6.updateIndex(DexMerger.java:502)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.merge.DexMerger$IdMerger.mergeSorted(DexMerger.java:277)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.merge.DexMerger.mergeMethodIds(DexMerger.java:491)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:168)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.merge.DexMerger.merge(DexMerger.java:189)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.command.dexer.Main.runMonoDex(Main.java:303)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.command.dexer.Main.run(Main.java:246)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.command.dexer.Main.main(Main.java:215)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.command.Main.main(Main.java:106)","sources":[{}]}

FAILED

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':app:dexDebug'.

    com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 2

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 13.002 secs


But when i remove compile 'io.socket:socket.io-client:0.6.1', sync and run the app.
Everything works fine. Please help.
Thanks in advance.

io.socket.engineio.client.EngineIOException: server error

try {
IO.Options options = new IO.Options();
options.query = "cookie=" + session + "&propname=sathish";
mSocket = IO.socket(AppController.URL, options);
app.setSocket(mSocket);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}

i am getting the error at connection stating that
io.socket.engineio.client.EngineIOException: server error

below is complete code

import android.os.Bundle;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.socket.client.Socket;
import io.socket.emitter.Emitter;

public class MainActivity extends AppCompatActivity {

private Socket mSocket;
private List<Message> mMessages = new ArrayList<Message>();
TextView response;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    response = (TextView) findViewById(R.id.response);

    AppController app = (AppController) getApplication();
    mSocket = app.getSocket();
    mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
    mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
    mSocket.on("connect", onConncet);
    mSocket.on("message", onNewMessage);
    mSocket.connect();

}

private Emitter.Listener onConnectError = new Emitter.Listener() {
    @Override
    public void call(final Object... args) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String str = args[0].toString();
                Log.d("see--->>", str);
                Toast.makeText(MainActivity.this, "Error Connection" + str, Toast.LENGTH_LONG).show();
            }
        });
    }
};

private Emitter.Listener onNewMessage = new Emitter.Listener() {
    @Override
    public void call(final Object... args) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                JSONObject data = (JSONObject) args[0];
                try {
                    Log.d("response from servaer", data.toString());
                    addLog(data.toString());
                    Toast.makeText(MainActivity.this, "Message" + data.toString(), Toast.LENGTH_LONG).show();
                    data.getString("");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
};

private Emitter.Listener onConncet = new Emitter.Listener() {
    @Override
    public void call(final Object... args) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d("Connect To servaer", "Connection Suicessfull");
                Toast.makeText(MainActivity.this, "Connection Successfull", Toast.LENGTH_LONG).show();
            }
        });
    }
};

private void addLog(String message) {
    response.setText(message);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mSocket.disconnect();
    mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
    mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
    mSocket.off("new message", onNewMessage);
}

}

Socket connection

node disconnect after app closed so how is it possible to node connect always no matter , app is in background or closed?

Send message to specific user from android device to other device

I'm implementing simple chat server that work fine in kind of browsers, but couldn't send message to specific user from android to other android device or android device to users which connected from browser, server said me user isn't connected, but in browser can detected correctly and sending message,i don't know whats problem, all of other feature work fine

Html for test and sending message to specific user:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>
        Document
    </title>
    </meta>
    <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#login').click(function () {
                socket.emit('login', {username: 'a', password: 'a'});
            });

            $('#mesage').click(function () {
                socket.emit('requestMoney', 'mahdi');
            });
        });
    </script>
    <script>
        var socket = new io.connect('http://192.168.1.35:3000', {
            port      : 3000,
            transports: ['websocket']
        });
        socket.on('connect', function () {
            console.log('connected!');
        });
        socket.on('message', function (message) {
            console.log("hello ::::::::" + message);
        });
        socket.on('success', function (data) {
            console.log(data);
        });
    </script>
</head>
<body>
<h3 id="login">login</h3>

<h3 id="mesage">mesage</h3>
</body>
</html>

My simplified nodejs server:

var socket      = require('socket.io'),
    express     = require('express'),
    app         = express(),
    server      = require('http').createServer(app),
    io          = socket.listen(server),
    port        = process.env.PORT || 3000,
    mysql       = require('mysql'),
    multer      = require('multer'),
    uuid        = require('node-uuid'),
    datetime    = require('node-datetime'),
    moment      = require('moment'),
    bcrypt      = require('bcrypt'),
    async       = require('async'),
    request     = require('request'),
    redis       = require("redis"),
    redisClient = redis.createClient(),
    log         = require('log4node');

var io_redis    = require('socket.io-redis');

io.adapter(io_redis({host: 'localhost', port: 6379}));

require('sticky-socket-cluster/replace-console')();

require('sticky-socket-cluster')(options, start);

function start(port) {
    io.sockets.on('connection', function (socket) {
        socket.on('login', function (data) {
            console.log(data.username);
            login(data.username, data.password, function (success, value) {
                if (success) {
                    redisClient.exists(data.username, function (err, doesExist) {
                        if (err) return;
                        if (!doesExist) {
                            log.info("saved to redis");

                            redisClient.set(data.username, socket.id, function (err, res) {
                                redisClient.set(data.username, socket.id);
                            });
                        }
                        else {
                            log.info("deleted and saved to redis");

                            redisClient.del(data.username);
                            redisClient.set(data.username, socket.id, function (err, res) {
                                redisClient.set(data.username, socket.id);
                            });
                        }
                    });
                    socket.emit('login', {result: true, id: value});
                } else {
                    log.info("FAIL login");
                    socket.emit('login', {result: false});
                }
            });
        });

        socket.on('requestMoney', function (data) {
            redisClient.get('mahdi', function (err, socketId) {
                if (io.sockets.connected[socketId]) {
                    log.info('mahdi' + ' sent');
                    io.sockets.connected[socketId].emit('message', {username: 'Hey to :), inja ro bebin ;)'});
                } else {
                    log.info('mahdi' + ' NOT LOGin');
                }
            });
        });

    });

    server.listen(port, function () {
        console.log('Express and socket.io listening on port ' + port);
    });
}

...

Android Socket settings and options:

public class Application extends android.app.Application {
    public static final boolean DEBUG = true;
    public static Application application;

    private static Context context;

    public static String    packageName;
    public static Resources resources;
    public static Socket    CHAT_SOCKET;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }
    @Override
    public void onCreate() {
        super.onCreate();

        //@formatter:off
            resources   = this.getResources();
            context     = getApplicationContext();
            packageName = getPackageName();
        //@formatter:on

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

        try {
            CHAT_SOCKET = IO.socket(ClientSettings.getChatAddress(), opts);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            Log.e("SOCKET.IO ", e.getMessage());
        }

    }

    public static Context getContext() {
        return context;
    }

    public Socket getSocket() {
        return CHAT_SOCKET;
    }
}

Failed on building project - Android studio 2.2.2

I tried to run this project on android studio 2.2.2
But it give me error

Failed to resolve:io.socket:socket.io-client:0.8.1

So I changed the dependencies like below

compile ('io.socket:socket.io-client:0.5.0') {
exclude group: 'org.json', module: 'json'
}

But same result.
Any advance ?

WaitingInMainSignalCatcherLoop

I am getting this excepition after sometime
Thread[2,tid=5533,WaitingInMainSignalCatcherLoop,Thread*=0xaf444400,peer=0x12c8b080,"Signal Catcher"]: reacting to signal 3
and am not able to connect again to server.
I am trying to connect to server from background service.
After connecting sometime later the connection get closed automatically and not reconnecting again.
How to handle this exception?
Is there any callback to handle this?
And am not able to view this stack traces.
Wrote stack traces to '/data/anr/traces.txt'

Thanks

is there a java server sample that can work with this project?

Hi,
since I cannot join the chat.socket.io , I tried to use a simple java server sample to run this project. But it show these log when I emit login event:

2016-12-12 10:31:47.386 ERROR 582 --- [ntLoopGroup-3-4] c.c.socketio.JsonSupportWrapper : Can't read value: ["chatevent","{userName:gg}"] for type: class com.corundumstudio.socketio.protocol.Event

And I check the json android client submit , find out the source code wrapped everything with jsonarray as above and it cannot be mapped to a com.corundumstudio.socketio.protocol.Event class. Please help, how can I make it run?

External messages to left

Hi, I would show external messages from the outside on the left side of the screen and messages sent by the myself on the right side of the screen. I've created two different item_message for the right side and for the left side, but I don't know how to implement this. Could you help me with a code snippet?
Thank you in advance.

Can't join chat on Android 6 (Nexus 6)

I have found issue when I try to run this demo on Android 6. "Join" button make no effect. On my Samsung Note 2 (Android 4.4.2) chat works like a charm.
Here is log:

  • /com.github.nkzawa.socketio.androidchat W/System: ClassLoader referenced unknown path: /data/app/com.github.nkzawa.socketio.androidchat-2/lib/arm
  • /com.github.nkzawa.socketio.androidchat D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
  • /com.github.nkzawa.socketio.androidchat I/Adreno: *QUALCOMM build : 52af4d2, I8366cd0437
    Build Date : 10/20/15
    OpenGL ES Shader Compiler Version: XE031.05.13.02
    Local Branch : M14
    Remote Branch :
    Remote Branch :
    Reconstruct Branch : *
  • /com.github.nkzawa.socketio.androidchat I/OpenGLRenderer: Initialized EGL, version 1.4

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.