Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io android java client receiving messages and sending file example

Does anyone have any sample code which demonstrates receiving messages on the java client side for socket.io?

Also, is there any example on sending a file/binary/picture over from the same socket.io java client? (basically sample code from java instead of javascript client)

The version of android java client can be acquired here (this version claim that it can be used with socket.io 1.0 and later) (seems to be the most updated version) https://github.com/nkzawa/socket.io-client.java

Currently the sample code which only allows me to initialize a connection, the server is able to get my incoming connection event and the java socket.io client is able to send out a basic emit message. However, there is no plain simple examples on how to acquire a message update from a server broadcast or emits from another website user.

Sample code just for reference:

package com.sample.d10132014a;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.github.nkzawa.socketio.client.*; // java socket io client
import com.github.nkzawa.socketio.client.Socket;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.engineio.client.*; // java engine io client
import com.github.nkzawa.engineio.client.transports.*;


public class MainActivity extends Activity {

    public static String internalPath; // internal storage path
    public static String fileName; // the file name
    private Socket socket; // socket object
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        try 
        {
            socket = IO.socket("http://YOURSERVERIP:3000");
            socket.connect();  // initiate connection to socket server
            socket.emit("chat message",  "From Android to server: 1st outgoing message");
        } 
        catch (URISyntaxException e) 
        {
            e.printStackTrace();
        }


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

          @Override
          public void call(Object... args) {
              Log.d("socketio", "socket connected");
              socket.emit("chat message", "even connect: message sent from android to socketio server");
              //socket.disconnect(); // why is there a disconnect here?
          }
      }).on("chat message", new Emitter.Listener() {

        @Override
        public void call(Object... arg0) {
            // TODO Auto-generated method stub
            JSONObject obj = (JSONObject)arg0[0];
            Log.d("socketio", "message back: "+obj.toString());
            Log.d("socketio", "incomming chat message: " + obj.toString() + arg0 + arg0[0] + arg0[1]); // trying to test which variable holds the message
        }
        }).on(Socket.EVENT_MESSAGE, new Emitter.Listener() {

            @Override
            public void call(Object... arg0) {
                // TODO Auto-generated method stub
                Log.d("socketio", "socket event message" + arg0);
                socket.emit("chat message", "android to server from event message");
            }
        });




      // 2nd segment test without connecting to 1 long method
      socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() 
      {
        @Override
        public void call(Object... arg0) {
            // TODO Auto-generated method stub
            Log.d("socketio", "socket event connect error");
            socket.emit("chat message",  "android to server: socket event connect error");
        }
      });

      socket.on(Socket.EVENT_MESSAGE, new Emitter.Listener() {

        @Override
        public void call(Object... arg0) {
            // TODO Auto-generated method stub
            Log.d("socketio", "socket event message" + arg0);
            socket.emit("chat message", "android to server from event message");
        }
    });
    setContentView(R.layout.activity_main);


    } // ending onCreate method

} // ending class

Thanks for reading

like image 846
Bigs Avatar asked Jan 10 '23 14:01

Bigs


2 Answers

Hy I am not sure if this is exactly what u are looking for, and there might be a chance that you have already solved it, regardless i would like to answer it as when i was browsing for a solution to my problem, i came across your question here but i couldnot find any answer, left me disappointed. As i have already solved my problem, i would like to share how i did it.

My problem was i was receiving the message from the node.js server but i could only see that message in my logcat and i was really having a problem to print that message on my android application in the main UI thread.

Lets say, we would show the message received from the server in the list view.

try {
        socket = IO.socket("http://192.168.1.10:3000");
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

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

        @Override
        public void call(Object... args) {
            Log.d("ActivityName: ", "socket connected");

            // emit anything you want here to the server
            socket.emit("login", some);
            //socket.disconnect();
        }

   // this is the emit from the server
    }).on("someFunction", new Emitter.Listener() {

        @Override
        public void call(Object... args) {
            // this argas[0] can have any type you send from the server
            JSONArray obj = (JSONArray) args[0];
              String message = obj.toString();

            // runOnUiThread is needed if you want to change something in the UI thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // do something
                    //mListData is the array adapter
                        mListData.add("Serversays" + " : " + " " + message);
                        mListData.notifyDataSetChanged();
                        lvList.setSelection(mListData.getCount() -1);
                }
            });
        }
    }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

        @Override
        public void call(Object... args) {
            Log.d("ActivityName: ", "socket disconnected");
        }

    });
    socket.connect();

we can update views only from main thread. You have to move the portion of the background task that updates the ui onto the main thread.So we have to add the following and do our required task in there.

runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
//do something
}
}

Hope it will save time for someone.

like image 99
Christine Avatar answered Jan 23 '23 05:01

Christine


Hi Hope the following implementation helps.Following is the manager class which keeps track of all event registration. passing callbacks, creating connection etc.

public class  NetworkManager {
    private static NetworkManager mInstance;
    private Socket mSocket;
    private int RECONNECTION_ATTEMPT = 10;
    private long CONNECTION_TIMEOUT = 30000;
    private static NetworkInterface mNetworkInterface;

    public static NetworkManager getInstance(Context context, NetworkInterface interfaces) {
        mNetworkInterface = interfaces;
        if (mInstance == null) {
            mInstance = new NetworkManager();
        }
        return mInstance;
    }

    /**
     * The purpose of this method to create the socket object
     */
    public void connectToSocket() {
        try {
            IO.Options opts = new IO.Options();
            opts.timeout = CONNECTION_TIMEOUT;
            opts.reconnection = true;
            opts.reconnectionAttempts = RECONNECTION_ATTEMPT;
            opts.reconnectionDelay = 1000;
            opts.forceNew = true;
            mSocket = IO.socket(NetworkConstant.SOCKET_CONNECTION_URL, opts);
           /*mSocket = IO.socket(NetworkConstant.SOCKET_CONNECTION_URL);
            mSocket.io().timeout(CONNECTION_TIMEOUT);
            mSocket.io().reconnection(true);
            mSocket.io().reconnectionAttempts(RECONNECTION_ATTEMPT);*/
            makeConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * The purpose of the method is to return the instance of socket
     *
     * @return
     */
    public Socket getSocket() {
        return mSocket;
    }

    /**
     * The purpose of this method is to connect with the socket
     */

    public void makeConnection() {
        if (mSocket != null) {
            mSocket.connect();
            if (mSocket.connected())
                registerConnectionAttributes();
        }
    }

    /**
     * The purpose of this method is to disconnect from the socket interface
     */
    public void disconnectFromSocket() {
        unregisterConnectionAttributes();
        mSocket.disconnect();
        mSocket = null;
        mInstance = null;
    }

    public void registerConnectionAttributes() {
        try {
            if(mSocket.connected()) {
                mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectionError);
                mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectionTimeOut);
                mSocket.on(Socket.EVENT_DISCONNECT, onServerDisconnect);
            }} catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void unregisterConnectionAttributes() {
        try {
            mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectionError);
            mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectionTimeOut);
            mSocket.off(Socket.EVENT_DISCONNECT, onServerDisconnect);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * The purpose of this method is to get the call back for any type of connection error
     */
    private Emitter.Listener onConnectionError = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Logger.error("Response", "onConnectionError");
            mNetworkInterface.networkCallReceive(NetworkConstant.SERVER_CONNECTION_ERROR);
        }
    };

    /**
     * The purpose of this method to get the call back for connection getting timed out
     */
    private Emitter.Listener onConnectionTimeOut = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Logger.error("Response", "onConnectionTimeOut");
            mNetworkInterface.networkCallReceive(NetworkConstant.SERVER_CONNECTION_TIMEOUT);
        }
    };
    /**
     * The purpose of this method is to receive the call back when the server get disconnected
     */
    private Emitter.Listener onServerDisconnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Logger.error("Response", "onServerDisconnection");
            mNetworkInterface.networkCallReceive(NetworkConstant.SERVER_DISCONNECTED);
        }
    };

    /**
     * The purpose of this method is register a method on server
     *
     * @param methodOnServer
     * @param handlerName
     */
    public void registerHandler(String methodOnServer, Emitter.Listener handlerName) {
        try {
            if(mSocket.connected())
            mSocket.on(methodOnServer, handlerName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * The purpose of this method is to unregister a method from server
     *
     * @param methodOnServer
     * @param handlerName
     */
    public void unRegisterHandler(String methodOnServer, Emitter.Listener handlerName) {
        try {
            mSocket.off(methodOnServer, handlerName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * The purpose of this method is to send the data to the server
     *
     * @param methodOnServer
     * @param request
     */
    public void sendDataToServer(String methodOnServer, JSONObject request) {
        Logger.error("JSON ", request.toString());
        try {
            if(mSocket.connected())

            {
                mSocket.emit(methodOnServer, request);
            }
            else
                {
                    mNetworkInterface.networkCallReceive(NetworkConstant.SERVER_CONNECTION_ERROR);
                }
            } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public interface NetworkInterface {
        public void networkCallReceive(int responseType);
    }

}
like image 26
Amardeep Avatar answered Jan 23 '23 06:01

Amardeep