socket Instant Messaging

rely:

//socket
implementation ('io.socket:socket.io-client:1.0.0') {
    // excluding org.json which is provided by Android
    exclude group: 'org.json', module: 'json'
}

when using it:

Socket socket;
try {
    socket = IO.socket(MyApp.baseSocketUrl));
    socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.d (the TAG, "Call: Socket Connected" );
            LoginSocketBean loginSocketBean = new LoginSocketBean(myApp.getUser_id());
            Gson gson = new Gson ();
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject (gson.toJson (loginSocketBean));
            } catch (JSONException e) {
                e.printStackTrace ();
            }
            Log.d (TAG, "Call: log" );
            socket.emit("user_login",jsonObject);
        }
    }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

        @Override
        public void call(Object... args) {
            Log.d (the TAG, "Call: Socket Disconnected" );
        }

    });
    socket.connect();
} catch (URISyntaxException e) {
    e.printStackTrace ();
    Log.d (TAG, "the onCreate: socket initialization failed" );
}

Above:

1, using the data transmitted to the server emit function (first argument represents the name of the event, as a server to determine the kind of event, the second parameter is the data transmission), where I is the transmitted data JSON format, string may be transmitted directly;

2, using the function on the received data monitor.

3, the socket initialization, using the connect function to connect, disconnect from the network will automatically reconnect the socket reconnection.

Guess you like

Origin www.cnblogs.com/zhaozilongcjiajia/p/11075693.html