简体   繁体   中英

Socket.io emit and listener functions not working on Android

I'm trying to connect my Android client to Node JS server using Socket.IO. Connection is successful but I can't emit or listen to any data change.

Here is my Android code...

 socket = IO.socket("http://192.168.0.101:3000");

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

                @Override
                public void call(Object... args) {
                    System.out.println("Connected");
                    socket.emit("message","test");
                }

            }).on("message", new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    System.out.println("Message : "+args[0]);
                }


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

                @Override
                public void call(Object... args) {
                    System.out.println("Socket disconnected");
                }

            }).on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    System.out.println("Error In Socket Connection "+args[0]);
                }
            });
            socket.connect();

Socket is connecting to server perfectly. I'm getting the "connected" message in log. But that "message" event isn't working. What am I doing wrong? ;_;

You need to use OkHttp. Add this to your Gradle dependencies:

implementation("com.squareup.okhttp3:okhttp:4.8.1")

Then add this as a field in the activity or fragment class:

private var socket: Socket? = null

Then this is how you get your socket instance for example in onCreate() method of the activity or fragment:

val okHttpClient: OkHttpClient = OkHttpClient.Builder().build()

IO.setDefaultOkHttpWebSocketFactory(okHttpClient)
IO.setDefaultOkHttpCallFactory(okHttpClient)

val opts = IO.Options()
opts.apply {
    callFactory = okHttpClient
    webSocketFactory = okHttpClient
}

socket = try {
    IO.socket("http://10.0.2.2:3000", opts)
} catch (e: URISyntaxException) {
    null
}

(This code is written in kotlin language)

Then everything should work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM