How to implement Instant Messaging in android using socket.io?

535 views Asked by At

I want to implement IM in an app that I am working on. I was suggested to use socket.io for this puropse. However, I am just a beginner in Android development. Basically, I just want users to be able to send simple string messages to each other.

So, I went through this github repo that uses socket.io in an Instant Messaging app. However I haven't understood anything from it. I just want to understand what each method does and when it should be called? How a message is sent and how a message is received? Could someone please provide a simple explanation of this code?

1

There are 1 answers

0
Muntaser Ahmed On BEST ANSWER

Socket.IO uses sockets to enable real-time bidirectional event-based communication between two nodes.

At a high level, to use Socket.IO in your application, you first need to create an instance of it. This will allow you to send and receive messages. For example:

private Socket mSocket;
mSocket = IO.socket("http://chat.socket.io");
mSocket.connect();

To send a message, you need to emit to an event. Let's call this event "new message". The following code sends a message using emit.

mSocket.emit("new message", message);

In a chat application, you would emit a new message when the user clicks the Send button.

Now that we know how to send a message, we need to know how to receive a message. To receive a message, you need to listen on an event, as opposed to emitting on an event.

mSocket.on("new message", onNewMessage);

The above line will listen for a "new message" event, and execute the behavior set in onNewMessage, which is a Listener. In your chat application, you can update the UI with the new message by adding the logic in your Listener.

To recap, you need to:

  1. Create a Socket.IO instance
  2. Emit a message when the user clicks Send.
  3. Listen for a message and update the UI.

Details on implementation can be found in Socket.IO's Android tutorial.

Hope this helps!