brief introduction
WebSocket is a new communication protocol of HTML5. It realizes two-way communication between browser and server. Socket.IO is an open source framework, which is completely implemented by JavaScript, based on Node.js and supports WebSocket protocols for real-time communication and cross-platform.
This article will be based on the official socket.io socket.io-android-chat Demo explains some of the basic operations of socket.io for instant messaging on android clients.
Attach the github link:
- Java Support Library socket.io-client-java
- Android Chat Demo socket.io-android-chat
Demo implements the following functions:
- Basic Text Chat Function
- Send notifications when each user joins or leaves
- Send notifications of input status when the user starts to enter information
Adding dependencies
The first step is to add a dependency to build.gradle, as follows:
compile ('io.socket:socket.io-client:0.8.3') {
// excluding org.json which is provided by Android
exclude group: 'org.json', module: 'json'
}
The second step is to register networking rights in AndroidManifest.xml
<!-- app/AndroidManifest.xml -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
...
</manifest>
Now we can use socket.IO in our project.~
Initialize Socket
We can get a Socket instance by IO.socket("URL"), where "URL" is the server address.
Socket mSocket = IO.socket("http://chat.socket.io");
Once the Socket instance is obtained, the connection () method is called to establish a connection with the server.
mSocket.connect();
The complete initialization code is as follows:
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
private Socket mSocket;
{
try {
//1.Initialization socket.io,Setting Links
mSocket = IO.socket("http://chat.socket.io");
} catch (URISyntaxException e) {}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//2.establish socket.ioConnection of servers
mSocket.connect();
}
Data transmission
We can send messages to the server through mSocket.emit("KEY", "VALUE"), KEY is the key of the event, VALUE is the value of the event, and the value supports any type of data.
Send a "new message" event to the server with the value of "hi":
mSocket.emit("new message", "hi~");
private EditText mInputMessageView;
//Method of sending messages
private void attemptSend() {
String message = mInputMessageView.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
return;
}
mInputMessageView.setText("");
mSocket.emit("new message", message);
}
Monitoring events
Socket.IO is a two-way transmission of information, which means that we can send events to the server at any time, and can also respond to events returned by the server at any time.
We can use mSocket.on("KEY", LISTENER) method to listen for events returned by the server. KEY is the key of the event, LISTENER is the listener, and the type of the listener is Emitter.Listener().
mSocket.on("new message", onNewMessage);
Following is an example of listening for new message events:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Use onNewMessage to listen for "new message" events from the server
mSocket.on("new message", onNewMessage);
mSocket.connect();
}
private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(final Object.. args) {
//Main thread call
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
String message;
try {
username = data.getString("username");
message = data.getString("message");
} catch (JSONException e) {
return;
}
// add the message to view
addMessage(username, message);
}
});
}
};
The Emitter.Listener() interface returns the data from the server in the call method. It should be noted that the call method is executed in the sub-thread. If we need to update the UI in the call method, we need to use handler or runOnUiThread to put the operation into the main thread to execute.
Releasing resources
To avoid memory leaks and other issues. When we finish using sockets, we need to disconnect the socket from the server and release the monitoring events of sockets.
disconnect the server:
mSocket.disconnect();
Call the off method to release the listening event:
mSocket.off("new message", onNewMessage);
At the end of the Activity, release the socket:
@Override
public void onDestroy() {
super.onDestroy();
mSocket.disconnect();
mSocket.off("new message", onNewMessage);
}