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:
- Create a Socket.IO instance
- Emit a message when the user clicks Send.
- Listen for a message and update the UI.
Details on implementation can be found in Socket.IO's Android tutorial.
Hope this helps!