Android Open Source - capture-the-flag Socket I O Network Client






From Project

Back to project page capture-the-flag.

License

The source code is released under:

Copyright ? 2014 Microsoft Mobile Oy. All rights reserved. Microsoft is a registered trademark of Microsoft Corporation. Nokia and HERE are trademarks and/or registered trademarks of Nokia Corporati...

If you think the Android project capture-the-flag listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*
 * Copyright (c) 2014 Microsoft Mobile. All rights reserved.
 * See the license text file provided with this project for more information.
 *///from   w  ww.ja  v  a2  s.co  m

package com.nokia.example.capturetheflag.network;

import java.util.Timer;
import java.util.TimerTask;

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

import android.os.Handler;
import android.util.Log;

import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.socketio.Acknowledge;
import com.koushikdutta.async.http.socketio.ConnectCallback;
import com.koushikdutta.async.http.socketio.EventCallback;
import com.koushikdutta.async.http.socketio.SocketIOClient;
import com.nokia.example.capturetheflag.network.model.Game;
import com.nokia.example.capturetheflag.network.model.Player;

/**
 * Socket I/O version of the network client, @see {@link NetworkClient}.
 */
public class SocketIONetworkClient
        extends NetworkClient
        implements ConnectCallback {
    public static final int DISCONNECT_TIMEOUT = 1000 * 60;
    private static final String TAG = "CtF/SocketIONetworkClient";
    private static final int MAX_RECONNECT_ATTEMPTS = 10;
    
    private Handler mHandler;
    private SocketIOClient mSocketClient;
    private JSONRequest queuedMessage;
    private Timer mTimer;
    private TimerTask mIdleTask;
    private String mUrl;
    private int mPort;
    private int mReconnectAttempts;

    public SocketIONetworkClient() {
        mHandler = new Handler();
        mTimer = new Timer();
    }

    public void connect(final String url, final int port) {
        if (mState == State.CONNECTED || mState == State.CONNECTING) {
            Log.d(TAG, "connect(): Already connected or trying to connect!");
            return;
        }
        
        mState = State.CONNECTING;
        mUrl = url;
        mPort = port;
        SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(),
                mUrl + ":" + mPort, this);
    }

    @Override
    public void onConnectCompleted(Exception ex, SocketIOClient client) {
        mSocketClient = client;
        
        if (ex != null) {
            mReconnectAttempts++;
            
            if (mReconnectAttempts > MAX_RECONNECT_ATTEMPTS) {
                Log.e(TAG, "Connection failed. Maximum number of reconnect attempts exceeded. Aborting...");
                disconnect();
                return;
            }
            
            Log.e(TAG, "Connection failed, trying to reconnect (attempt "
                    + mReconnectAttempts + "/" + MAX_RECONNECT_ATTEMPTS
                    + ")..." /*, ex*/);
            
            mSocketClient.reconnect();
            return;
        }

        mState = State.CONNECTED;
        mReconnectAttempts = 0;
        mListener.onNetworkStateChange(true, SocketIONetworkClient.this);

        if (queuedMessage != null) {
            Log.d(TAG, "Sending message from queue");
            JSONArray arr = new JSONArray();
            arr.put(queuedMessage.getRequestData());
            client.emit(queuedMessage.getEventName(), arr);
            queuedMessage = null;
        }

        client.addListener("gamelist", new EventCallback() {
            @Override
            public void onEvent(final JSONArray argument, Acknowledge acknowledge) {
                Log.d(TAG, "Game list event: " + argument.toString());

                try {
                    JSONObject msg = argument.getJSONObject(0);
                    JSONArray arr = msg.getJSONArray("games");
                    Game[] games = new Game[arr.length()];

                    for (int i = 0; i < arr.length(); i++) {
                        Game g = new Game(arr.getJSONObject(i));
                        games[i] = g;
                    }

                    final GameListResponse resp = new GameListResponse();
                    resp.setGames(games);

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mListener != null) {
                                mListener.onGameListMessage(resp);
                            }
                        }
                    });
                } catch (Exception e) {
                    Log.e(TAG, "JSON error: ", e);
                }
            }
        });

        client.addListener("joined", new EventCallback() {
            @Override
            public void onEvent(JSONArray argument, Acknowledge acknowledge) {
                try {
                    JSONObject obj = argument.getJSONObject(0);
                    final JoinedResponse joined = new JoinedResponse();
                    JSONObject gameObj = obj.getJSONObject("game");
                    joined.setJoinedGame(new Game(gameObj));
                    Log.d(TAG, "Joined response parsed");
                    joined.setPlayer(new Player(obj.getJSONObject("player")));

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mListener != null) {
                                mListener.onJoinedMessage(joined);
                            }
                        }
                    });
                } catch (JSONException je) {
                    Log.e(TAG, "JSON error: ", je);
                }
            }
        });

        client.addListener("update-player", new EventCallback() {
            @Override
            public void onEvent(JSONArray argument, Acknowledge acknowledge) {
                try {
                    JSONObject obj = argument.getJSONObject(0);
                    Player p = new Player(obj.getJSONObject("update-player"));
                    final UpdatePlayerResponse resp = new UpdatePlayerResponse();
                    resp.setUpdatedPlayer(p);

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mListener != null) {
                                mListener.onUpdatePlayerMessage(resp);
                            }
                        }
                    });
                } catch (JSONException e) {
                    Log.e(TAG, "JSON error: ", e);
                }
            }
        });

        client.addListener("error", new EventCallback() {
            @Override
            public void onEvent(JSONArray argument, Acknowledge acknowledge) {
                try {
                    JSONObject errorObj = argument.getJSONObject(0);
                    final JSONResponse resp = new JSONResponse();
                    resp.setErrorCode(errorObj.optInt("code", -100));

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mListener != null) {
                                mListener.onError(resp);
                            }
                        }
                    });
                } catch (JSONException e) {
                    Log.e(TAG, "JSON error: ", e);
                }
            }
        });
    }

    public synchronized void emit(JSONRequest request) {
        if (mSocketClient != null) {
            if (!mSocketClient.isConnected()) {
                Log.d(TAG, "Adding the request to the queue and trying to reconnect...");
                mSocketClient.reconnect();
                queuedMessage = request;
                return;
            }

            Log.d(TAG, "Sending: " + request.getEventName());
            JSONArray args = new JSONArray();

            if (request.getRequestData() != null) {
                args.put(request.getRequestData());
            }

            mSocketClient.emit(request.getEventName(), args);
        } else {
            Log.d(TAG, "Adding the request to the queue");
            queuedMessage = request;
        }
    }

    public void disconnect() {
        if (mSocketClient != null) {
            mSocketClient.disconnect();

            if (mListener != null) {
                mListener.onNetworkStateChange(false, SocketIONetworkClient.this);
            }
        }

        mState = State.IDLE;
        mReconnectAttempts = 0;
    }

    @Override
    public boolean isConnected() {
        if (mSocketClient != null) {
            return mSocketClient.isConnected();
        }

        return false;
    }

    @Override
    public void setConnectionIdle(boolean isIdle) {
        if (isIdle) {
            mIdleTask = new TimerTask() {
                @Override
                public void run() {
                    if (mSocketClient != null) {
                        Log.d(TAG, "Idle, disconnecting...");
                        mSocketClient.disconnect();
                        mState = State.IDLE;
                        mReconnectAttempts = 0;
                    }
                }
            };

            mTimer.schedule(mIdleTask, DISCONNECT_TIMEOUT);
        } else {
            if (mIdleTask != null) {
                boolean isCanceled = mIdleTask.cancel();

                if (!isCanceled) {
                    if (mSocketClient != null) {
                        Log.d(TAG, "Not idle anymore, waking up...");
                        connect(mUrl, mPort);
                    }
                }
            }
        }
    }

    @Override
    public void cleanUp() {
        mListener = null;

        if (isConnected()) {
            disconnect();
        }
    }
}




Java Source Code List

com.nokia.example.capturetheflag.AboutActivity.java
com.nokia.example.capturetheflag.Controller.java
com.nokia.example.capturetheflag.CreateGameFragment.java
com.nokia.example.capturetheflag.GameEndedDialogFragment.java
com.nokia.example.capturetheflag.GameMenuFragment.java
com.nokia.example.capturetheflag.HelpActivity.java
com.nokia.example.capturetheflag.JoinGameFragment.java
com.nokia.example.capturetheflag.MainActivity.java
com.nokia.example.capturetheflag.PauseDialog.java
com.nokia.example.capturetheflag.PurchasePremiumFragment.java
com.nokia.example.capturetheflag.ServerSettingsDialog.java
com.nokia.example.capturetheflag.Settings.java
com.nokia.example.capturetheflag.location.LocationManagerBase.java
com.nokia.example.capturetheflag.location.LocationManagerFactory.java
com.nokia.example.capturetheflag.location.LocationManagerInterface.java
com.nokia.example.capturetheflag.location.LocationManagerListener.java
com.nokia.example.capturetheflag.location.LocationUtils.java
com.nokia.example.capturetheflag.location.google.LocationManagerGoogle.java
com.nokia.example.capturetheflag.location.here.LocationManagerHere.java
com.nokia.example.capturetheflag.map.GameMapFactory.java
com.nokia.example.capturetheflag.map.GameMapInterface.java
com.nokia.example.capturetheflag.map.GameMapUtils.java
com.nokia.example.capturetheflag.map.MarkerFactoryBase.java
com.nokia.example.capturetheflag.map.google.GameMapGoogle.java
com.nokia.example.capturetheflag.map.google.MarkerFactoryGoogle.java
com.nokia.example.capturetheflag.map.here.GameMapHere.java
com.nokia.example.capturetheflag.map.here.MarkerFactoryHere.java
com.nokia.example.capturetheflag.network.FlagCapturedResponse.java
com.nokia.example.capturetheflag.network.GameListRequest.java
com.nokia.example.capturetheflag.network.GameListResponse.java
com.nokia.example.capturetheflag.network.JSONRequest.java
com.nokia.example.capturetheflag.network.JSONResponse.java
com.nokia.example.capturetheflag.network.JoinRequest.java
com.nokia.example.capturetheflag.network.JoinedResponse.java
com.nokia.example.capturetheflag.network.NetworkClient.java
com.nokia.example.capturetheflag.network.OfflineClient.java
com.nokia.example.capturetheflag.network.SocketIONetworkClient.java
com.nokia.example.capturetheflag.network.UpdatePlayerRequest.java
com.nokia.example.capturetheflag.network.UpdatePlayerResponse.java
com.nokia.example.capturetheflag.network.model.Flag.java
com.nokia.example.capturetheflag.network.model.Game.java
com.nokia.example.capturetheflag.network.model.ModelConstants.java
com.nokia.example.capturetheflag.network.model.Player.java
com.nokia.example.capturetheflag.notifications.NotificationsManagerBase.java
com.nokia.example.capturetheflag.notifications.NotificationsManagerFactory.java
com.nokia.example.capturetheflag.notifications.NotificationsManagerInterface.java
com.nokia.example.capturetheflag.notifications.NotificationsUtils.java
com.nokia.example.capturetheflag.notifications.google.GcmBroadcastReceiver.java
com.nokia.example.capturetheflag.notifications.google.GcmIntentService.java
com.nokia.example.capturetheflag.notifications.google.NotificationsManagerGoogle.java
com.nokia.example.capturetheflag.notifications.nokia.NokiaNotificationsBroadcastReceiver.java
com.nokia.example.capturetheflag.notifications.nokia.NokiaNotificationsIntentService.java
com.nokia.example.capturetheflag.notifications.nokia.NotificationsManagerNokia.java