Advertisement
Guest User

Smartfox Connection

a guest
Sep 3rd, 2015
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.05 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using System;
  4. using System.Collections;
  5. using Sfs2X;
  6. using Sfs2X.Logging;
  7. using Sfs2X.Util;
  8. using Sfs2X.Core;
  9. using Sfs2X.Entities;
  10. using Sfs2X.Entities.Data;
  11. using Sfs2X.Requests;
  12.  
  13. public class SmartfoxConnectionHandler : MonoBehaviour {
  14.    
  15.     //----------------------------------------------------------
  16.     // UI elements
  17.     //----------------------------------------------------------
  18.     public static SmartfoxConnectionHandler REF;
  19.     public bool doLogin;
  20.     public bool useLagMonitor;
  21.  
  22.     public delegate void OnLoggedIn(SFSObject aLoginInfo,SFSArray aHorses);
  23.     public OnLoggedIn onLoggedIn;
  24.  
  25.     //----------------------------------------------------------
  26.     // Private properties
  27.     //----------------------------------------------------------
  28.    
  29.     protected SmartFox sfs;
  30.    
  31.     /*
  32.          * IMPORTANT NOTE
  33.          * Protocol encryption requires a specific setup of SmartFoxServer 2X and a valid SSL certificate.
  34.          * For this reason it is disabled by default in this example. If you want to test it, please read
  35.          * this document carefully before proceeding: http://docs2x.smartfoxserver.com/GettingStarted/cryptography
  36.          * The code performing the encryption initialization is provided here for reference,
  37.          * showing how to handle it when building for different platforms.
  38.          */
  39.  
  40.     //----------------------------------------------------------
  41.     // Unity calback methods
  42.     //----------------------------------------------------------
  43.    
  44.     void Start() {
  45.         REF = this;
  46.         // Start connecting after 1 second
  47.         StartCoroutine(autoConnect());
  48.     }
  49.    
  50.     private IEnumerator autoConnect() {
  51.         yield return new WaitForSeconds(1f);
  52.         this.doConnectToServer();
  53.     }
  54.     void Update() {
  55.         // As Unity is not thread safe, we process the queued up callbacks on every frame
  56.         if (sfs != null)
  57.             sfs.ProcessEvents();
  58.     }
  59.     public bool isConnected {
  60.         get {
  61.             if(sfs==null) {
  62.                 return false;
  63.             }
  64.             return sfs.IsConnected;
  65.         }
  66.     }
  67.    
  68.     // Disconnect from the socket when shutting down the game
  69.     // ** Important for Windows users - can cause crashes otherwise
  70.     public void OnApplicationQuit() {
  71.         if (sfs != null && sfs.IsConnected)
  72.             sfs.Disconnect();
  73.        
  74.         sfs = null;
  75.     }
  76.    
  77.     // Disconnect from the socket when ordered by the main Panel scene
  78.     // ** Important for Windows users - can cause crashes otherwise
  79.     public void Disconnect() {
  80.         OnApplicationQuit();
  81.     }
  82.    
  83.     //----------------------------------------------------------
  84.     // Public interface methods for UI
  85.     //----------------------------------------------------------
  86.  
  87.     public void doConnectToServer() {
  88.         if (sfs == null || !sfs.IsConnected) {
  89.            
  90.             // Initialize SFS2X client and add listeners
  91.             // WebGL build uses a different constructor
  92.             #if !UNITY_WEBGL
  93.                 sfs = new SmartFox();
  94.             #else
  95.                 sfs = new SmartFox(UseWebSocket.WS);
  96.             #endif
  97.            
  98.             // Set ThreadSafeMode explicitly, or Windows Store builds will get a wrong default value (false)
  99.             sfs.ThreadSafeMode = true;
  100.            
  101.             sfs.AddEventListener(SFSEvent.CONNECTION, OnConnection);
  102.             sfs.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost);
  103.             sfs.AddEventListener(SFSEvent.CRYPTO_INIT, OnCryptoInit);
  104.             sfs.AddEventListener(SFSEvent.LOGIN, OnLogin);
  105.             sfs.AddEventListener(SFSEvent.LOGIN_ERROR, OnLoginError);
  106.             sfs.AddEventListener(SFSEvent.EXTENSION_RESPONSE, OnExtensionResponse);
  107.             sfs.AddEventListener(SFSEvent.PING_PONG, OnPingPong);
  108.            
  109.         /*  sfs.AddLogListener(LogLevel.DEBUG, OnDebugMessage);
  110.             sfs.AddLogListener(LogLevel.INFO, OnInfoMessage);
  111.             sfs.AddLogListener(LogLevel.WARN, OnWarnMessage);*/
  112.             sfs.AddLogListener(LogLevel.ERROR, OnErrorMessage);
  113.             // Set connection parameters
  114.             ConfigData cfg = new ConfigData();
  115.            
  116.            
  117.             cfg.Port = 9933;
  118.             #if !UNITY_WEBGL
  119.                 cfg.Host = "64.91.226.4";
  120.             #endif
  121.             #if UNITY_WEBGL
  122.                 cfg.HttpPort = 8888;
  123.                 cfg.Host = "64.91.226.4";
  124.             #endif
  125.             cfg.Zone = "HA3D";
  126.             cfg.Debug = false;
  127.            
  128.             // Connect to SFS2X
  129.  
  130.             // Debug.Log("Client Version: "+sfs.Version);
  131.             sfs.Connect(cfg);
  132.         } else {
  133.            
  134.             // DISCONNECT
  135.            
  136.             // Disable button
  137.            
  138.             // Disconnect from SFS2X
  139.             sfs.Disconnect();
  140.         }
  141.     }
  142.     // Public methods for sending messages to the server
  143.  
  144.     public void sendMessage(string aCommand,SFSObject aObject) {
  145.         if(sfs.IsConnected) {
  146.             sfs.Send(new ExtensionRequest(aCommand,aObject));
  147.         }
  148.     }
  149.     public void sendHorsesArray(string aCommand,SFSArray aHorses)
  150.     {
  151.         SFSObject p = new SFSObject();
  152.         p.PutSFSArray("horses",aHorses);
  153.         sfs.Send(new ExtensionRequest(aCommand,p,null));
  154.     }
  155.  
  156.  
  157.     //----------------------------------------------------------
  158.     // Private helper methods
  159.     //----------------------------------------------------------
  160.    
  161.     private void enableInterface(bool enable) {
  162.        
  163.     }
  164.    
  165.     private void trace(string msg) {
  166.         Debug.Log (msg);
  167.     }
  168.    
  169.     private void reset() {
  170.         // Remove SFS2X listeners
  171.         sfs.RemoveEventListener(SFSEvent.CONNECTION, OnConnection);
  172.         sfs.RemoveEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost);
  173.         sfs.RemoveEventListener(SFSEvent.CRYPTO_INIT, OnCryptoInit);
  174.         sfs.RemoveEventListener(SFSEvent.LOGIN, OnLogin);
  175.         sfs.RemoveEventListener(SFSEvent.LOGIN_ERROR, OnLoginError);
  176.         sfs.RemoveEventListener(SFSEvent.PING_PONG, OnPingPong);
  177.        
  178.         sfs.RemoveLogListener(LogLevel.DEBUG, OnDebugMessage);
  179.         sfs.RemoveLogListener(LogLevel.INFO, OnInfoMessage);
  180.         sfs.RemoveLogListener(LogLevel.WARN, OnWarnMessage);
  181.         sfs.RemoveLogListener(LogLevel.ERROR, OnErrorMessage);
  182.        
  183.         sfs = null;
  184.        
  185.         // Enable interface
  186.         enableInterface(true);
  187.     }
  188.    
  189.     public void login(string aUsername) {
  190.             sfs.Send(new Sfs2X.Requests.LoginRequest(aUsername,""));
  191.     }
  192.    
  193.     //----------------------------------------------------------
  194.     // SmartFoxServer event listeners
  195.     //----------------------------------------------------------
  196.     private void OnExtensionResponse(BaseEvent evt) {
  197.         Debug.Log ("Extension response received");
  198.         string cmd = (string)evt.Params["cmd"];
  199.         SFSObject dataObject = (SFSObject)evt.Params["params"];
  200.        
  201.         switch ( cmd ) {
  202.         case "z_l":
  203.                 SFSArray userArr = (SFSArray) dataObject.GetSFSArray("user");
  204.                 SFSArray horsesArr = (SFSArray) dataObject.GetSFSArray("horses");
  205.                 SFSArray brandsArr = (SFSArray) dataObject.GetSFSArray("b");
  206.                 int consecDaysLoggedIn = (int) dataObject.GetInt("consec");
  207.  
  208.                 SFSObject userObj = (SFSObject) userArr.GetSFSObject(0);
  209.                 BrandLibrary.REF.initFromSmartfox(brandsArr);
  210.                 this.onLoggedIn(userObj,horsesArr);
  211.                 Debug.Log ("Got User Object: "+userObj+" horses object: "+horsesArr.Size());
  212.             break;
  213.         }
  214.        
  215.     }
  216.     private void OnConnection(BaseEvent evt) {
  217.         if ((bool)evt.Params["success"]) {
  218.             trace("Connection established successfully");
  219.             trace("SFS2X API version: " + sfs.Version);
  220.             trace("Connection mode is: " + sfs.ConnectionMode);
  221.            
  222.             // Enable disconnect button
  223.  
  224.         } else {
  225.             trace("Connection failed; is the server running at all?");
  226.            
  227.             // Remove SFS2X listeners and re-enable interface
  228.             reset();
  229.         }
  230.     }
  231.    
  232.     private void OnConnectionLost(BaseEvent evt) {
  233.         trace("Connection was lost; reason is: " + (string)evt.Params["reason"]);
  234.        
  235.         // Remove SFS2X listeners and re-enable interface
  236.         reset();
  237.     }
  238.    
  239.     private void OnCryptoInit(BaseEvent evt) {
  240.         if ((bool) evt.Params["success"])
  241.         {
  242.             trace("Encryption initialized successfully");
  243.            
  244.             // Attempt login
  245.     //      login();
  246.         } else {
  247.             trace("Encryption initialization failed: " + (string)evt.Params["errorMessage"]);
  248.         }
  249.     }
  250.    
  251.     private void OnLogin(BaseEvent evt) {
  252.         User user = (Sfs2X.Entities.User)evt.Params["user"];
  253.        
  254.         trace("Login successful");
  255.         trace("Username is: " + user.Name);
  256.         // Now we want to send z_l to the server
  257.         SFSObject sfsObj = new SFSObject();
  258.         // Set our current version
  259.         sfsObj.PutUtfString("V","3D1");
  260.         sfsObj.PutInt("ID",Convert.ToInt32(user.Name));
  261.         // Get the login info for this user
  262.         this.sendMessage("l",sfsObj);
  263.         // Enable lag monitor
  264.         if (useLagMonitor)
  265.             sfs.EnableLagMonitor(true);
  266.     }
  267.    
  268.     private void OnLoginError(BaseEvent evt) {
  269.         trace("Login failed: " + (string) evt.Params["errorMessage"]);
  270.     }
  271.    
  272.     private void OnPingPong(BaseEvent evt) {
  273.         trace("Measured lag is: " + (int) evt.Params["lagValue"] + "ms");
  274.     }
  275.    
  276.     //----------------------------------------------------------
  277.     // SmartFoxServer log event listeners
  278.     //----------------------------------------------------------
  279.    
  280.     public void OnDebugMessage(BaseEvent evt) {
  281.         string message = (string)evt.Params["message"];
  282.         ShowLogMessage("DEBUG", message);
  283.     }
  284.    
  285.     public void OnInfoMessage(BaseEvent evt) {
  286.         string message = (string)evt.Params["message"];
  287.         ShowLogMessage("INFO", message);
  288.     }
  289.    
  290.     public void OnWarnMessage(BaseEvent evt) {
  291.         string message = (string)evt.Params["message"];
  292.         ShowLogMessage("WARN", message);
  293.     }
  294.    
  295.     public void OnErrorMessage(BaseEvent evt) {
  296.         string message = (string)evt.Params["message"];
  297.         ShowLogMessage("ERROR", message);
  298.     }
  299.    
  300.     private void ShowLogMessage(string level, string message) {
  301.         message = "[SFS > " + level + "] " + message;
  302.         trace(message);
  303.         Debug.Log(message);
  304.     }
  305. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement