Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add realtime-connection-management sample

  • Loading branch information...
commit 6e700daa40dc2fad0cb58ef1b45b494fc2c0c197 1 parent a176ce4
@capflam capflam authored
View
1  realtime/realtime-connection-management/.gitignore
@@ -0,0 +1 @@
+SDK/*
View
33 realtime/realtime-connection-management/README.md
@@ -0,0 +1,33 @@
+Realtime-connection-management sample
+=====================================
+
+To use this sample you have to:
+
+* Create an account on the [Scoreflex platform](http://developer.scoreflex.com/
+ "Scoreflex developer site") (if you don't have one already).
+* Create a game -or modify an existing one- (check the **Web** option in the
+ list of available platforms).
+* Checkout this sample and copy the [Scoreflex Javascript
+ SDK](https://github.com/scoreflex/scoreflex-javascript-sdk "Scoreflex
+ Javascript SDK on GitHub") to the `SDK/` folder (sample tested with the
+ realtime branch)
+* Edit the *game.js* file and update the `clientId` and `clientSecret` variables
+ with your game's identifiers.
+
+------
+
+The realtime-connection-management sample focuses on the following Scoreflex SDK features:
+
+* Manage lifecycle of the realtime session:
+ - Manage Scoreflex SDK initialization/deinitialization
+ - Handle player login/logout events
+ - Manage realtime session initialization/deinitialization
+* Manage the realtime connection
+
+Typical use-cases covered by this sample:
+
+* Use Restart/Stop buttons to test initialization/deinitialization of the SDK
+ and the realtime session.
+* Use login/logout from the user's profile WebView to test the player changes.
+* Use Connect/Disconnect buttons to open/close connection on the realtime
+ service.
View
0  realtime/realtime-connection-management/SDK/copyScoreflexSDKHere
No changes.
View
65 realtime/realtime-connection-management/game.css
@@ -0,0 +1,65 @@
+HTML,
+BODY {
+ margin:0;
+ padding:0;
+}
+BODY {
+ font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;
+}
+
+#infoDiv {
+ margin: 1em;
+ padding-left: 0.5em;
+ border: 1px solid #000;
+ width: 750px;
+ height: 600px;
+ overflow-y: scroll;
+ line-height: 80%;
+}
+#infoDiv .infoDate {
+ display: inline;
+ font-size: 13px;
+ margin-right: 5px;
+}
+#infoDiv .infoTxt {
+ display: inline;
+}
+#infoDiv .infoTxt PRE {
+ display: inline;
+ margin: 0;
+}
+
+#restartDiv {
+ margin: 1em;
+ width: 750px;
+ text-align: center;
+}
+
+BUTTON {
+ padding:0.3em 1em;
+ font-size:1em;
+ font-weight:bold;
+ border-radius:5px;
+ box-shadow:0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05);
+ margin:0.2em;
+ cursor:pointer;
+ border:1px solid transparent;
+}
+BUTTON.enabled {
+ background-color: #6E7273;
+ border-color: rgba(0, 0, 0, 0.25) rgba(0, 0, 0, 0.35) rgba(0, 0, 0, 0.35) rgba(0, 0, 0, 0.25);
+ color: #FFFFFF;
+ text-shadow: 0 -1px 0 #505455;
+}
+
+BUTTON.disabled {
+ border-color: rgba(0, 0, 0, 0.25) rgba(0, 0, 0, 0.35) rgba(0, 0, 0, 0.35) rgba(0, 0, 0, 0.25);
+ color: #FFFFFF;
+}
+
+.scoreflexWebClient_full {
+ height: 800px;
+ position: absolute;
+ right: 0;
+ top: 0;
+ width: 480px;
View
26 realtime/realtime-connection-management/game.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>Realtime connection management sample</title>
+ <link href="./game.css" type="text/css" rel="stylesheet">
+ </head>
+ <body>
+ <div id="restartDiv">
+ <button id="restartButton" class="disabled">Restart</button>
+ <button id="stopButton" class="disabled">Stop</button>
+ <button id="connectionButton" class="disabled">Connect</button>
+ <button id="showProfileButton" class="disabled">Player's profile</button>
+ <button id="clearLogButton" class="enabled">Clear log</button>
+ </div>
+ <div id="infoDiv"></div>
+ <script type="text/javascript" src="./SDK/libs/CryptoJS/rollups/hmac-sha1.js"></script>
+ <script type="text/javascript" src="./SDK/libs/CryptoJS/components/enc-base64-min.js"></script>
+ <script type="text/javascript" src="./SDK/libs/Json/json2.js"></script>
+ <script type="text/javascript" src="./SDK/libs/ProtoBuf/Long.js"></script>
+ <script type="text/javascript" src="./SDK/libs/ProtoBuf/ByteBuffer.js"></script>
+ <script type="text/javascript" src="./SDK/libs/ProtoBuf/ProtoBuf.js"></script>
+ <script type="text/javascript" src="./SDK/scoreflex.js"></script>
+ <script type="text/javascript" src="./SDK/scoreflexRealtime.js"></script>
+ <script type="text/javascript" src="./game.js"></script>
+ </body>
+</html>
View
306 realtime/realtime-connection-management/game.js
@@ -0,0 +1,306 @@
+var myGame = new (function MyGame() {
+ /**********************************************************************/
+ /*********************** Scoreflex identifiers ************************/
+ /**********************************************************************/
+ // FILL THESE VARIABLES
+ var gameName = 'Realtime connection management sample';
+ var clientId = '...';
+ var clientSecret = '...';
+ var useSandbox = true;
+
+
+ /**********************************************************************/
+ /**************************** My variables ****************************/
+ /**********************************************************************/
+ // Define Scoreflex objects
+ var scoreflex = null;
+ var realtimeSession = null;
+
+ // Retrieve DOM elements
+ var infoEl = document.getElementById("infoDiv");
+ var restartButtonEl = document.getElementById("restartButton");
+ var stopButtonEl = document.getElementById("stopButton");
+ var connectionButtonEl= document.getElementById("connectionButton");
+ var profileButtonEl = document.getElementById("showProfileButton");
+ var clearButtonEl = document.getElementById("clearLogButton");
+ clearButtonEl.onclick = function() { infoEl.innerHTML = ''; };
+
+
+ /**********************************************************************/
+ /*************************** Misc functions ***************************/
+ /**********************************************************************/
+ // Return the current time. Used to log messages
+ var getTime = function() {
+ var date = new Date();
+ var time = date.toLocaleTimeString();
+ var ms = date.getMilliseconds();
+ if (ms < 10)
+ return ("["+time+ ".00"+ms+"]");
+ else if (ms < 100)
+ return ("["+time+ ".0"+ms+"]");
+ return ("["+time+ "."+ms+"]");
+ };
+
+ // Add a log message in the info box, prefixed by the current time.
+ var logInfo = function(msg) {
+ msg = msg.replace(/\n/g, "<br>");
+ infoEl.innerHTML += '<div class="infoLine">'
+ + '<span class="infoDate">'+getTime()+'</span>'
+ + '<span class="infoTxt"><pre>'+msg+'</pre></span>'
+ + '</div>';
+ };
+
+ // Helper function to register a listener on a specified event target
+ var listenEvent = function(element, eventType, handler) {
+ if(element.addEventListener) {
+ element.addEventListener(eventType, handler, false);
+ }
+ else if(element.attachEvent) {
+ element.attachEvent( "on" + eventType, handler);
+ }
+ };
+
+
+ // Initialize the scoreflex SDK:
+ // 1. The scoreflex object is destroyed, if needed
+ // 2. Buttons state is reset
+ // 3. The opened scoreflex webview is closed, if any
+ // 4. The scoreflex object is created (with a delay, for testing purpose)
+ var initializeSDK = function() {
+ if (scoreflex) {
+ deinitializeSDK();
+ }
+
+ logInfo("Scoreflex SDK initializing...");
+ restartButtonEl.className = "disabled";
+ restartButtonEl.onclick = null;
+ stopButtonEl.className = "disabled";
+ stopButtonEl.onclick = null;
+ connectionButtonEl.className= "disabled";
+ connectionButtonEl.onclick = null;
+ profileButtonEl.className = "disabled";
+ profileButtonEl.onclick = null;
+
+ var el = document.getElementById("scoreflexWebClient_full");
+ if (el) {
+ document.body.removeChild(el);
+ }
+
+ setTimeout(function() {
+ scoreflex = new Scoreflex(clientId, clientSecret, useSandbox);
+ }, 1000);
+ };
+
+ // Deinitialize the scoreflex SDK
+ // 1. Buttons state is reset
+ // 2. The realtime session is destroyed
+ // 3. The scoreflex object is destroyed
+ var deinitializeSDK = function() {
+ logInfo("Scoreflex SDK deinitializing...");
+ restartButtonEl.className = "enabled";
+ restartButtonEl.onclick = function() { initializeSDK(); };
+ stopButtonEl.className = "disabled";
+ stopButtonEl.onclick = null;
+ profileButtonEl.className = "disabled";
+ profileButtonEl.onclick = null;
+ connectionButtonEl.className= "disabled";
+ connectionButtonEl.onclick = null;
+ stopRealtimeSession();
+ scoreflex.destroy();
+ scoreflex = null;
+ logInfo("Scoreflex SDK deinitialized");
+ };
+
+ // Retrieve the realtime session and initialize it
+ // 1. Retrieve the realtime session for the current player
+ // 2. Initialize it and wait the result
+ var startRealtimeSession = function() {
+ logInfo("Scoreflex realtime session initializing...");
+ realtimeSession = scoreflex.getRealtimeSession();
+ if (!realtimeSession.isInitialized()) {
+ realtimeSession.initialize(realtimeSessionInitializedListener);
+ }
+ else {
+ realtimeSessionInitializedListener.onInitialized();
+ }
+ };
+
+ // Destroy the realtime session, if needed
+ var stopRealtimeSession = function() {
+ logInfo("Scoreflex realtime session deinitializing...");
+ if (realtimeSession) {
+ if (realtimeSession.isConnected()) {
+ disconnectRealtimeSession();
+ }
+ scoreflex.destroyRealtimeSession();
+ }
+ realtimeSession = null;
+ };
+
+ var connectRealtimeSession = function() {
+ connectionButtonEl.className= "disabled";
+ realtimeSession.connect(connectionListener);
+ };
+
+ var disconnectRealtimeSession = function() {
+ connectionButtonEl.className= "enabled";
+ connectionButtonEl.innerHTML= "Connect";
+ connectionButtonEl.onclick = function() { connectRealtimeSession(); };
+ realtimeSession.disconnect();
+ logInfo("Connection state: DISCONNECTED");
+ };
+
+ /**********************************************************************/
+ /**************************** Event listeners *************************/
+ /**********************************************************************/
+ // Main scoreflex event handler:
+ // - catch the scorefles SDK initialization result, the 'session' events
+ // - catch player login/logout, the 'player' events
+ //
+ // ignore 'challenge' and 'play' events for now.
+ var scoreflexEventHandler = function(event) {
+ var eventData = event.detail || {};
+
+ // Handle session events
+ if (eventData.name === 'session') {
+ if (eventData.state === Scoreflex.SessionState.INIT_SUCCESS) {
+ // The Scoreflex SDK was successfully initialized. Now, start
+ // the realtime session.
+ logInfo("Scoreflex SDK initialized");
+ profileButtonEl.className = "enabled";
+ profileButtonEl.onclick = function() { scoreflex.Players.getCurrent().showProfile(); };
+ startRealtimeSession();
+ }
+ else if (eventData.state === Scoreflex.SessionState.INIT_FAILED) {
+ logInfo("Scoreflex SDK initialization failed");
+ restartButtonEl.className = "enabled";
+ restartButtonEl.onclick = function() { initializeSDK(); };
+ stopButtonEl.className = "disable";
+ stopButtonEl.onclick = null;
+ }
+ }
+
+ // Handle player events
+ else if (eventData.name === 'player') {
+ logInfo(((eventData.anonymous === true) ? "Anonymous" : "Authenticated")
+ +" player logged-in");
+ if (scoreflex.getSessionState() === Scoreflex.SessionState.INIT_SUCCESS) {
+ // The scoreflex SDK was already initialized, so this event was
+ // launched because the current player has changed. In this
+ // situation, we destroy the current realtime session and start
+ // a new one.
+ logInfo("Current player has changed. Renew the realtime session");
+ stopRealtimeSession();
+ startRealtimeSession();
+ }
+ }
+ };
+
+ // Realtime session listener:
+ // - catch the realtime session initialization/deinitialization events
+ var realtimeSessionInitializedListener = {
+ onInitialized: function() {
+ // The realtime session was successfully initialized, so we print
+ // some information about it.
+ logInfo("Scoreflex realtime session initialized\n"
+ + " * Server address: "+realtimeSession.getServerAddr()+"\n"
+ + " * Session options:\n"
+ + " - Auto reconnection flag: "+realtimeSession.getReconnectFlag()+"\n"
+ + " - Max retries: "+realtimeSession.getMaxRetries()+"\n"
+ + " - Reconnection timeout: "+realtimeSession.getReconnectTimeout()+" msecs");
+
+ // Set new buttons state
+ restartButtonEl.className = "enabled";
+ restartButtonEl.onclick = function() { initializeSDK(); };
+ stopButtonEl.className = "enabled";
+ stopButtonEl.onclick = function() { deinitializeSDK(); };
+ connectionButtonEl.className= "enabled";
+ connectionButtonEl.onclick = function() { connectRealtimeSession(); };
+ },
+
+ onInitializationFailed: function(status) {
+ // The realtime session initialization failed
+ switch (status) {
+ case Scoreflex.Realtime.StatusCode.STATUS_NETWORK_ERROR:
+ logInfo("Scoreflex realtime session initialization failed\n"
+ + " (reason: Network error)");
+ break;
+ case Scoreflex.Realtime.StatusCode.STATUS_PERMISSION_DENIED:
+ logInfo("Scoreflex realtime session initialization failed\n"
+ + " (reason: Permission denied)\n");
+ break;
+ case Scoreflex.Realtime.StatusCode.STATUS_INTERNAL_ERROR:
+ logInfo("Scoreflex realtime session initialization failed\n"
+ + " (reason: Internal error)");
+ break;
+ default:
+ logInfo("Scoreflex realtime session initialization failed\n"
+ + " (reason: Unexpected error)");
+ }
+ restartButtonEl.className = "enabled";
+ restartButtonEl.onclick = function() { initializeSDK(); };
+ stopButtonEl.className = "disabled";
+ stopButtonEl.onclick = null;
+ },
+
+ onDeInitialized: function() {
+ logInfo("Scoreflex realtime session deinitialized.\n");
+ realtimeSession = null;
+ }
+ };
+
+ // Realtime connection listener:
+ // - catch connection status changes
+ var connectionListener = {
+ onConnected: function(info) {
+ // New connection was opened. Print some information about the
+ // session
+ var sessInfo = {msg: ""};
+ realtimeSession.getSessionInfo().forEach(function(k,v,t) {
+ this.msg += " * "+k+": "+v+"\n";
+ }, sessInfo);
+ logInfo("Connection state: CONNECTED\n"+sessInfo.msg);
+
+ connectionButtonEl.className= "enabled";
+ connectionButtonEl.innerHTML= "Disconnect";
+ connectionButtonEl.onclick = function() { disconnectRealtimeSession(); };
+
+ // ################################################################
+ // THIS SAMPLE ENDS HERE. CHECKOUT 'realtime-room-management' SAMPLE
+ // FOR THE NEXT STEPS.
+ // ################################################################
+ },
+ onConnectionFailed: function(status) {
+ logInfo("Connection state: DISCONNECTED\n"
+ + " (connection failed - error: "+status+")");
+
+ connectionButtonEl.className= "enabled";
+ connectionButtonEl.innerHTML= "Connect";
+ connectionButtonEl.onclick = function() { connectRealtimeSession(); };
+ },
+ onConnectionClosed: function(status) {
+ logInfo("Connection state: DISCONNECTED\n"
+ + " (connection closed - reason: "+status+")");
+
+ connectionButtonEl.className= "enabled";
+ connectionButtonEl.innerHTML= "Connect";
+ connectionButtonEl.onclick = function() { connectRealtimeSession(); };
+ },
+ onReconnecting: function(status) {
+ logInfo("Connection state: RECONNECTING\n"
+ + " (reason: "+status+")");
+ connectionButtonEl.className= "disabled";
+ }
+ };
+
+ /**********************************************************************/
+ /************************* Object initialization **********************/
+ /**********************************************************************/
+ // Register The scoreflex event handler and initialiaze the scoreflex SDK
+ listenEvent(window, 'ScoreflexEvent', scoreflexEventHandler);
+ initializeSDK();
+
+ // Export main objects for testing purpose
+ this.scoreflex = function() { return scoreflex; };
+ this.realtimeSession = function() { return realtimeSession; };
+})();
Please sign in to comment.
Something went wrong with that request. Please try again.