简体   繁体   中英

How can to send POST/GET with params via socket.io or call a feathersjs service via socket.io in Android?

I just finished my application in NodeJs using feathersjs . Now I write an app on android to communicate with my services by node side. How can I communicate with node service like find/get/create/update via android socket?

Below is my snippet code:

try {
    mSocket = IO.socket("http://10.0.130.32:3030");
} catch (URISyntaxException e) {
    e.printStackTrace();
}

mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

    @Override
    public void call(Object... args) {
       // socket.emit("foo", "hi");
       // socket.disconnect();
    }

}).on("config", new Emitter.Listener() {

    /*
     * Android joins to a room after receiving socket's id from another user
     */

    @Override
    public void call(Object... args) {

        try {
            JSONObject object = new JSONObject(args[0].toString());
            mSocket.emit("join", object.get("socket"));
            id = object.getString("socket");
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

    @Override
    public void call(Object... args) {}

});
mSocket.connect();

I know that you can use: mSocket.emit("join", "some data"); but I would like call a REST Api for example: http://10.0.130.32:3030/getID in Android via socket with params.

How can I do that?

With Feathers, you are able to access all service methods (find/get/create/etc) from either REST or Sockets.

From the docs: https://docs.feathersjs.com/clients/vanilla-socket-io.html

Calling service methods

Service methods can be called by emitting a <servicepath>::<methodname> event with the method parameters. servicepath is the name the service has been registered with (in app.use) without leading or trailing slashes. An optional callback following the function(error, data) Node convention will be called with the result of the method call or any errors that might have occurred.

params will be set as params.query in the service method call. Other service parameters can be set through a Socket.io middleware.

You can find a lot of examples on that page, but as an idea:

socket.emit('messages::find', { status: 'read', user: 10 }, (error, data) => {
  console.log('Found all messages', data);
});

Note that you'll need the socket pointed to the root of your feathers app: 10.0.130.32:3030

In Android for REST Api calls we use HttpURLConnection. For example for GET:

String url = "http://10.0.130.32:3030/getID";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM