Skip to content

Instantly share code, notes, and snippets.

@aksel
Last active February 12, 2021 11:35
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aksel/b3e986e2aa14ac78ec3fde87bd960312 to your computer and use it in GitHub Desktop.
Save aksel/b3e986e2aa14ac78ec3fde87bd960312 to your computer and use it in GitHub Desktop.
Kotlin Socket.IO example connection function.
import io.socket.client.IO
import io.socket.client.Socket
fun connect() {
val socket = IO.socket("http://localhost:4000?user=aksel")
socket.connect()
.on(Socket.EVENT_CONNECT, { println("connected") })
.on(Socket.EVENT_DISCONNECT, { println("disconnected") })
}
@aksel
Copy link
Author

aksel commented Aug 5, 2017

This gist is an example connect function.
It connects to a socketio server, hosted at localhost, on port 4000.
It passes a username "aksel" in the queryparams.

An equivalent Javascript socket connection would look something like this:

const socket = io({ query: { user: 'aksel' } });
socket.on('connect', () => console.log('connected'));
socket.on('disconnect', () => console.log('disconnected'));

@90K2
Copy link

90K2 commented Jun 27, 2018

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

@sonickseven
Copy link

And @aksel with Ack() ?

java code

sockets.mSocket.emit("socketID", data, new Ack() {
    @Override
    public void call(Object... args) {
        JSONObject repues = (JSONObject) args[0];
        // todo with repues
    }
});

Javascript code

sockets.emit("socketID", data, repues=>{
    // todo with repues
});

@SupertigerDev
Copy link

What if i wanna access socket in multiple kt files or activities in android?

@stivenson
Copy link

cool, man @aksel , thanks, please to check your gradle file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment