Sunday, 7 May 2017

Socket url connect/disconnect every time while passing message form android

Hello friends i integrate socket.io for chat implementation so below is my code.

In my application class i define my socket class

private Socket mSocket;

{
    try {
        mSocket = IO.socket("http://212.47.235.49:3000/);
        mSocket.connect();
    } catch (URISyntaxException e) {
        System.out.println("exception");
        throw new RuntimeException(e);
    }
}

public  Socket getSocket() {
    return mSocket;
}

In my Activity class i use socket class as below

MyApplication app = (MyApplication) mActivity.getApplication();
        mSocket = app.getSocket();
        mSocket.emit("add user", name);
        mSocket.on("login", onLogin);

onLogin Emit function

private Emitter.Listener onLogin = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        JSONObject data = (JSONObject) args[0];

        int numUsers;
        try {
            numUsers = data.getInt("numUsers");
        } catch (JSONException e) {
            return;
        }

        Intent intent = new Intent();
        intent.putExtra("username", name);
        intent.putExtra("numUsers", numUsers);
        intent.putExtra("chat_id", chat_id);
        intent.putExtra("from_id", from_id);
        mActivity.setResult(RESULT_OK, intent);
    }
};

MyApplication app = (MyApplication) getApplication();
    mSocket = app.getSocket();
    mSocket.on(Socket.EVENT_CONNECT, onConnect);
    mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
    mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
    mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
    mSocket.on("new message", onNewMessage);

    System.out.println("Socket id " + mSocket.id());
    System.out.println("Socket connected " + mSocket.connected());

    mSocket.on("typing", onTyping);
    mSocket.on("stop typing", onStopTyping);
    mSocket.connect();
    System.out.println("Socket id " + mSocket.id());
    System.out.println("Socket connected " + mSocket.connected());

When i run above code i m getting error message like soket DISCONNECT: Disconnected, Please check your internet connection Any idea how can i solve this?



via Harshal Kalavadiya

No comments:

Post a Comment