示例#1
0
    public static Socket CreateTCPServer(int port, int version, Action <Socket> connected)
    {
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        UnityThreadHelper.CreateThread(() => {
            try
            {
                listener.Bind(new IPEndPoint(IPAddress.Any, port));
                listener.Listen(LISTEN_BUFFER);

                // Start listening for connections.
                while (true)
                {
                    // Thread sleeps while waiting for an incoming connection
                    Socket handler = listener.Accept();
                    // Handle data in Closure
                    connected(handler);

                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            catch (Exception e)
            {
            }
            finally
            {
                listener.Close();
            }
        });

        return(listener);
    }
示例#2
0
    public static void EnsureHelper()
    {
        lock (syncRoot)
        {
#if !NO_UNITY
            if (null == (object)instance)
            {
                instance = FindObjectOfType(typeof(UnityThreadHelper)) as UnityThreadHelper;
                if (null == (object)instance)
                {
                    var go = new GameObject("[UnityThreadHelper]");
                    go.hideFlags = HideFlags.NotEditable | HideFlags.HideInHierarchy | HideFlags.HideInInspector;
                    instance = go.AddComponent<UnityThreadHelper>();
                    instance.EnsureHelperInstance();
                }
            }
#else
		    if (null == instance)
		    {
			    instance = new UnityThreadHelper();
			    instance.EnsureHelperInstance();
		    }
#endif
        }
    }
示例#3
0
    public static UdpClient CreateUDPServer(int port, Action <IPEndPoint, byte[]> messageReceived)
    {
        UdpClient  listener      = new UdpClient(port);
        IPEndPoint groupEndPoint = new IPEndPoint(IPAddress.Any, port);

        UnityThreadHelper.CreateThread(() =>
        {
            try
            {
                while (true)
                {
                    byte[] receivedBytes = listener.Receive(ref groupEndPoint);
                    messageReceived(groupEndPoint, receivedBytes);
                }
            }
            catch (Exception e)
            {
            }
            finally
            {
                listener.Close();
            }
        });

        return(listener);
    }
    private void resetPassword()
    {
        UserManager um = new UserManager();

        SceneManager.LoadScene("Loader", LoadSceneMode.Additive);
        UnityThreadHelper.CreateThread(() =>
        {
            bool?res = um.updatePassword(Email.text, newPassword.text);
            UnityThreadHelper.Dispatcher.Dispatch(() =>
            {
                SceneManager.UnloadSceneAsync("Loader");
                if (res == false)
                {
                    showconnectionFailed();
                }
                else
                {
                    if (res == null)
                    {
                        showconnectionFailed();
                    }
                    else
                    {
                    }
                }
            });
        });
    }
示例#5
0
 public void OnDisable()
 {
     if (instance == this)
     {
         instance = null;
     }
 }
示例#6
0
 public void ConfigNextRewardTime()
 {
     if (nextRewardTime == DateTime.MinValue)
     {
         userId = um.getCurrentUserId();
         token  = um.getCurrentSessionToken();
         Loader.gameObject.SetActive(true);
         UnityThreadHelper.CreateThread(() => {
             User user = um.getUser(userId, token);
             UnityThreadHelper.Dispatcher.Dispatch(() => {
                 Loader.gameObject.SetActive(false);
                 if (user != null)
                 {
                     if (string.IsNullOrEmpty(user.last_bubble_click))
                     {
                         nextRewardTime = DateTime.MinValue;
                     }
                     else
                     {
                         nextRewardTime = Convert.ToDateTime(user.last_bubble_click).ToUniversalTime().AddHours(rewardIntervalHours);
                     }
                 }
                 else
                 {
                     nextRewardTime = DateTime.MinValue;
                 }
                 checkTimer();
             });
         });
     }
     else
     {
         checkTimer();
     }
 }
示例#7
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Wall" || collision.gameObject.tag == "Pod" || collision.gameObject.tag == "Player")
        {
            var heading = collision.contacts[0].point - (Vector2)transform.position;
            newDirection         = Vector3.Reflect(heading, collision.contacts[0].normal).normalized;
            randomStartDirection = newDirection;
        }
        else if (collision.gameObject.tag == "Bullet")
        {
            if (!canHit)
            {
                return;
            }

            health--;
            RegisterHitAt(collision.GetContact(0).point);
            if (health <= 0)
            {
                canHit = false;
                var explosion = (GameObject)Instantiate(destroyEffectPrefab, transform.position, Quaternion.identity);
                Destroy(explosion, 4f);
                killPodThread = UnityThreadHelper.CreateThread(KillPod);
                Destroy(canvasGo);
                Destroy(gameObject, 0.2f);
            }
        }
    }
    void CheckOpponent()
    {
        UserManager      um     = new UserManager();
        string           token  = um.getCurrentSessionToken();
        string           userID = um.getCurrentUserId();
        ChallengeManager cm     = new ChallengeManager();

        UnityThreadHelper.CreateThread(() =>
        {
            var N = cm.getChallengebyId(ChallengeManager.CurrentChallengeId, token);
            UnityThreadHelper.Dispatcher.Dispatch(() =>
            {
                if (!string.IsNullOrEmpty(N["data"]["matched_user_1"]["_id"].Value) && !string.IsNullOrEmpty(N["data"]["matched_user_2"]["_id"].Value))
                {
                    if (N["data"]["matched_user_1"]["_id"].Value.Equals(userID))
                    {
                        OpponentFound.adversaireName = N["data"]["matched_user_2"]["username"];
                        OpponentFound.Avatar         = N["data"]["matched_user_2"]["avatar"];
                        OpponentFound.AdvCountryCode = N["data"]["matched_user_2"]["country_code"];
                    }
                    else
                    {
                        OpponentFound.adversaireName = N["data"]["matched_user_1"]["username"];
                        OpponentFound.Avatar         = N["data"]["matched_user_1"]["avatar"];
                        OpponentFound.AdvCountryCode = N["data"]["matched_user_1"]["country_code"];
                    }
                    EventsController.advFound = true;
                }
            });
        });
    }
示例#9
0
        public void saveConfig(Console console)
        {
            FileInfo info = null;

            UnityThreadHelper.CreateThread(() => {
                try {
                    info = new FileInfo(configPath);
                    info.Delete();
                } catch (System.Exception e) {
                    Debug.Log(e);
                }

                try {
                    StreamWriter writer = new StreamWriter(configPath);

                    writer.WriteLine(username.Trim());
                    writer.WriteLine(password.Trim());

                    if (explicitPathToRepository != null)
                    {
                        writer.WriteLine(explicitPathToRepository.Trim());
                    }

                    writer.Close();

                    console.credentials          = new Credentials();
                    console.credentials.Username = username.Trim();
                    console.credentials.Password = password.Trim();
                } catch (System.Exception e) {
                    Debug.Log(e);
                }
            });
        }
示例#10
0
    void OnDestroy()
    {
        Debug.Log("OnDestroy UTH called");
        foreach (var thread in registeredThreads)
        {
            Debug.Log("Disposing a thread...");
            thread.Dispose();
        }


        if (dispatcher != null)
        {
            dispatcher.Dispose();
        }
        dispatcher = null;

        if (taskDistributor != null)
        {
            taskDistributor.Dispose();
        }
        taskDistributor = null;

        if (instance == this)
        {
            instance = null;
        }
    }
示例#11
0
    public static void EnsureHelper()
    {
        lock (syncRoot)
        {
#if !NO_UNITY
            if (null == (object)instance)
            {
                instance = FindObjectOfType(typeof(UnityThreadHelper)) as UnityThreadHelper;
                if (null == (object)instance)
                {
                    var go = new GameObject("[UnityThreadHelper]");
                    go.hideFlags = HideFlags.NotEditable | HideFlags.HideInHierarchy | HideFlags.HideInInspector;
                    instance     = go.AddComponent <UnityThreadHelper>();
                }
                instance.EnsureHelperInstance();
            }
#else
            if (null == instance)
            {
                instance = new UnityThreadHelper();
                instance.EnsureHelperInstance();
            }
#endif
        }
    }
 public override void performAsync()
 {
     UnityThreadHelper.CreateThread((Action) delegate
     {
         send();
     });
 }
示例#13
0
 /// <summary>
 /// Processes all remaining tasks. Call this periodically to allow the Dispatcher to handle dispatched tasks.
 /// Only call this inside the thread you want the tasks to process to be processed.
 /// </summary>
 public void ProcessTasks()
 {
     //Debug.Log("DEBUG 1");
     if (UnityThreadHelper.IsWebPlayer ? UnityThreadHelper.WaitOne(dataEvent, 0) : dataEvent.WaitOne(0, false))
     {
         ProcessTasksInternal();
     }
     //Debug.Log("DEBUG 2");
 }
        private void OnEnable()
        {
            nb_players.text = nbPlayer;
            username.text   = UserManager.Get.CurrentUser.username;
            var mTexture  = new Texture2D(1, 1);
            var flagBytes = Convert.FromBase64String(PlayerPrefs.GetString("CurrentFlagBytesString"));

            mTexture.LoadImage(flagBytes);
            user_flag.sprite   = Sprite.Create(mTexture, new Rect(0f, 0f, mTexture.width, mTexture.height), Vector2.zero);
            user_avatar.sprite = UserManager.Get.CurrentAvatarBytesString;

            gain.text  = ChallengeManager.CurrentChallenge.gain.ToString();
            gain.text += (ChallengeManager.CurrentChallenge.gain_type.Equals(ChallengeManager.CHALLENGE_WIN_TYPE_BUBBLES)) ? " bubbles" : " €";
            InvokeRepeating("CheckOpponent", .5f, 3f);

            try
            {
                int count = 10;
                UnityThreadHelper.CreateThread(() =>
                {
                    while (count > 0)
                    {
                        Thread.Sleep(1000);
                        UnityThreadHelper.Dispatcher.Dispatch(() =>
                        {
                            if ((10 - count) == 3)
                            {
                                try
                                {
                                    Continue.transform.localScale = Vector3.one;
                                }
                                catch (NullReferenceException)
                                {
                                }
                            }
                            if ((10 - count) == 9)
                            {
                                try
                                {
                                    looking_for_opponent.transform.localScale = Vector3.one;
                                    start_now.transform.localScale            = Vector3.zero;
                                    same_game.transform.localScale            = Vector3.zero;
                                }
                                catch (NullReferenceException)
                                {
                                }
                            }
                            counter.text = count.ToString();
                        });
                        count--;
                    }
                });
            }
            catch (NullReferenceException)
            {
            }
        }
示例#15
0
    // Use this for initialization
    void Start()
    {
        TestPackBuilder.main();           //初始化
        UnityThreadHelper.EnsureHelper(); //线程初始化,这个必须要在开始定义.

        CustomTrace.close(true);          //关闭输出。关闭框架输出,如果影响调试。

        TinyPlayerCS pp = new TinyPlayerCS();

        pp.id = 2009;


        client = new Client();

        client.testUint((uint)3312);

        //client.testPlayer.addEventListener("onOpen", onCSOpen);

        Debug.Log("是否解决了?");
        client.onSocketCloseCS = onSocketClose;
        client.onSocketOpenCS  = onSocketOpen;
        client.onSocketErrorCS = onSocketError;
        //  client.connectWithIP("27.102.127.81", 9003); //这里改成你自己的ip
        client.connectWithIP("127.0.0.1", 9003); //这里改成你自己的ip
        //  client.connectWithIP("144.48.4.186", 9003); //这里改成你自己的ip
        client.onGlobalError = onGlobalError;
        // client.testPlayer.dispatchEvent(new CEvent("onOpen"),this );


        self = new PlayerCS(null);
        self.addEvent(); //这里添加倾听器,如果要移除用off
        self.addEventListener(HallEvent.LOGIN, onLogin);

        self.addEventListener(HallEvent.OnReg, onReg);

        self.addEventListener(PlayerEvent.GET_USER_INFO, onGetuserInfo);

        self.addEventListener(PlayerEvent.GET_TEARM_INCOME, onGetIncome);
        self.addEventListener(ShoppingEvent.GET_BUY_LIST, onGetBuyList);
        self.addEventListener(ShoppingEvent.GET_CHARGE_LIST, onGetChargeList);
        self.addEventListener(ShoppingEvent.GET_DRAW_OUT_LIST, onGetDrawOutList);
        self.addEventListener(ShoppingEvent.GET_LAST_CHARGE_TIME, onGetLastChargeTime);
        self.addEventListener(PlayerEvent.STATIC_CHANGE, onStatusChange);
        self.addEventListener(PlayerEvent.ADD_BET, onPlayerAddBet);
        self.addEventListener(RoomEvent.JOIN_ROOM, onJoinRoom);
        self.addEventListener(ShoppingEvent.GET_REATE, onGetRate);
        TestEventDispathFromHaxe();


        //---------------新增-------------------
        hall = new HallCS(); //创建大厅
        hall.addEvent();     //这个一定不能删除。//todo:不能其他人登陆会影响到这里。
        hall.addEventListener(RoomEvent.CREATE_ROOM, onCreateRoom);
        hall.addEventListener(RoomEvent.JOIN_ROOM, onJoinRoom);
        hall.addEventListener(CMDEvent.RESULT, onCMDResult);
    }
    public void SaveGame()
    {
        tmpObject = GameObject.Find("SaveAndLoadManager");

        if (tmpObject != null)
        {
            saveManager = tmpObject.GetComponent("SaveAndLoad") as SaveAndLoad;
            saveThread  = UnityThreadHelper.CreateThread((System.Action)saveManager.SaveGame);
        }
    }
示例#17
0
 public void HandleRewardBasedVideoRewarded(object sender, Reward args)
 {
     UnityThreadHelper.executeInUpdate(() => {
         if (OnReward != null)
         {
             OnReward();
             OnReward = null;
         }
     });
 }
    public void LoadGame()
    {
        getManager = GameObject.Find("SaveAndLoadManager");

        if (getManager != null)
        {
            loadManager = getManager.GetComponent("SaveAndLoad") as SaveAndLoad;
            loadThread  = UnityThreadHelper.CreateThread((System.Action)loadManager.LoadGame);
        }
    }
示例#19
0
        public async void creditClick()
        {
            if (string.IsNullOrEmpty(UserManager.Get.CurrentUser.country_code))
            {
                UserManager.Get.CurrentUser.country_code = await UserManager.Get.GetGeoLoc();
            }

            if (CountryController.checkCountry(UserManager.Get.CurrentUser.country_code))
            {
                StartCoroutine(EventsController.Get.checkInternetConnection(async(isConnected) =>
                {
                    LoaderManager.Get.LoaderController.HideLoader();
                    if (isConnected == true)
                    {
                        if (Add5Euro.IsSelected)
                        {
                            await Add5Euro.AddAmountAsync();
                        }
                        else if (Add10Euro.IsSelected)
                        {
                            await Add10Euro.AddAmountAsync();
                        }
                        else if (Add15Euro.IsSelected)
                        {
                            await Add15Euro.AddAmountAsync();
                        }
                        else if (Add20Euro.IsSelected)
                        {
                            await Add20Euro.AddAmountAsync();
                        }
                        else
                        {
                            await AddOtherAmount.AddOtherAmountAsync();
                        }
                    }
                    else
                    {
                        ConnectivityController.CURRENT_ACTION = ConnectivityController.CREDIT_ACTION;
                        PopupManager.Get.PopupController.ShowPopup(PopupType.INFO_POPUP_CONNECTION_FAILED, PopupsText.Get.ConnectionFailed());
                    }
                }));
            }
            else
            {
                UnityThreading.ActionThread thread;
                thread = UnityThreadHelper.CreateThread(() =>
                {
                    Thread.Sleep(300);
                    UnityThreadHelper.Dispatcher.Dispatch(() =>
                    {
                        PopupManager.Get.PopupController.ShowPopup(PopupType.INFO_POPUP_PROHIBITED_LOCATION_WALLET, PopupsText.Get.ProhibitedLocationWallet());
                    });
                });
            }
        }
 /// <summary>
 /// Blocks the calling thread until the task has been ended or the given timeout value has been reached.
 /// </summary>
 /// <param name="seconds">Time in seconds this method will max wait.</param>
 public void WaitForSeconds(float seconds)
 {
     if (UnityThreadHelper.IsWebPlayer)
     {
         UnityThreadHelper.WaitOne(endedEvent, TimeSpan.FromSeconds(seconds));
     }
     else
     {
         endedEvent.WaitOne(TimeSpan.FromSeconds(seconds));
     }
 }
示例#21
0
 public void missingInfowithdrawContinue()
 {
     UnityThreading.ActionThread thread;
     thread = UnityThreadHelper.CreateThread(() =>
     {
         Thread.Sleep(300);
         UnityThreadHelper.Dispatcher.Dispatch(() =>
         {
             ViewsEvents.Get.GoToMenu(ViewsEvents.Get.IdProof.gameObject);
         });
     });
 }
示例#22
0
 public void ReconnectExipiredSession()
 {
     UnityThreading.ActionThread thread;
     thread = UnityThreadHelper.CreateThread(() =>
     {
         Thread.Sleep(100);
         UnityThreadHelper.Dispatcher.Dispatch(() =>
         {
             ViewsEvents.Get.GoToMenu(ViewsEvents.Get.Login.gameObject);
         });
     });
 }
示例#23
0
    void updateHeader()
    {
        UserManager um     = new UserManager();
        string      userid = um.getCurrentUserId();
        string      token  = um.getCurrentSessionToken();

        UnityThreadHelper.CreateThread(() => {
            User usr = um.getUser(userid, token);
            if (usr != null)
            {
                Byte[] lnByte = um.getAvatar(usr.avatar);
                UnityThreadHelper.Dispatcher.Dispatch(() => {
                    UserManager.CurrentMoney = usr.money_credit.ToString("N2");
                    UserManager.CurrentWater = usr.bubble_credit.ToString();
                    GameObject.Find("virtual_money").GetComponent <Text>().text = UserManager.CurrentWater;
                    GameObject.Find("solde_euro").GetComponent <Text>().text    = UserManager.CurrentMoney + " " + CurrencyManager.CURRENT_CURRENCY;
                    if (usr.money_credit > 0)
                    {
                        GameObject.Find("Pro").transform.localScale = Vector3.one;
                    }
                    else
                    {
                        GameObject.Find("Pro").transform.localScale = Vector3.zero;
                    }
                    if (UserManager.CurrentAvatarURL != usr.avatar)
                    {
                        Sprite avatar = ImagesManager.getSpriteFromBytes(lnByte);
                        UserManager.CurrentAvatarBytesString = avatar;
                        Image PlayerAvatar  = GameObject.Find("Avatar").GetComponent <Image> ();
                        PlayerAvatar.sprite = avatar;
                    }

                    UserManager.CurrentUsername = usr.username;
                    Text username = GameObject.Find("Text_name").GetComponent <Text> ();
                    username.text = usr.username;
                    PullToRefresh.walletFinished = true;
                    InvokeRepeating("hideAnimation", 0f, 0.5f);
                });
            }
            else
            {
                UnityThreadHelper.Dispatcher.Dispatch(() => {
                    lastResultfinished = true;
                    ongoingfinished    = true;
                    walletFinished     = true;
                    InvokeRepeating("hideAnimation", 0f, 2f);
                    HomeController.GetComponent <HomeController>().enabled = false;
                    HomeController.GetComponent <HomeController>().enabled = true;
                });
            }
        });
    }
示例#24
0
    public WeChatTool()
    {
        UnityThreadHelper.EnsureHelper();
#if UNITY_EDITOR
#elif UNITY_ANDROID
        using (var mWeChatTool = new AndroidJavaClass("com.wechat.WeChatTool"))
        {
            wechat = mWeChatTool.CallStatic <AndroidJavaObject>("Create", AppID);
        }
#elif UNITY_IOS
        WechatInit(AppID, Schemes);
#endif
    }
示例#25
0
    public void StartClient(string nickname)
    {
        client          = new Client(new TcpClient());
        client.Nickname = nickname;
        client.CurrentClient.Connect("192.168.0.87", 6969);
        stream = client.CurrentClient.GetStream();

        LoginData loginData = new LoginData(client.Nickname, "");

        SendRequest(client, (byte)RequestTypes.Login, loginData);

        clientThread = UnityThreadHelper.CreateThread(ClientThread);
    }
示例#26
0
 public void missingInfoContinue()
 {
     UnityThreading.ActionThread thread;
     thread = UnityThreadHelper.CreateThread(() =>
     {
         Thread.Sleep(300);
         UnityThreadHelper.Dispatcher.Dispatch(() =>
         {
             PopupManager.Get.PopupViewPresenter.HidePopupContent(PopupManager.Get.PopupController.PopupInfo);
             ViewsEvents.Get.GoToMenu(ViewsEvents.Get.PersonalInfo.gameObject, true);
         });
     });
 }
示例#27
0
 public void continuePayment()
 {
     PopupManager.Get.PopupViewPresenter.HidePopupContent(PopupManager.Get.PopupController.PopupPayment);
     UnityThreading.ActionThread myThread;
     myThread = UnityThreadHelper.CreateThread(() =>
     {
         Thread.Sleep(700);
         UnityThreadHelper.Dispatcher.Dispatch(() =>
         {
             ViewsEvents.Get.GoToMenu(ViewsEvents.Get.BankingInfo.gameObject);
         });
     });
 }
示例#28
0
    public SugramTool()
    {
        UnityThreadHelper.EnsureHelper();
#if UNITY_EDITOR
#elif UNITY_ANDROID
        using (var mSugramTool = new AndroidJavaClass("com.sugram.SugramTool"))
        {
            schemes = mSugramTool.CallStatic <AndroidJavaObject>("Create", AppID);
        }
#elif UNITY_IOS
        //SugramInit(AppID,Schemes);
#endif
    }
示例#29
0
    public static void SendTCPCommand(IPAddress address, int port, byte[] data, Action <Socket> response)
    {
        UnityThreadHelper.CreateThread(() =>
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(new IPEndPoint(address, port));

            socket.Send(data);
            response(socket);

            socket.Close();
            return;
        });
    }
示例#30
0
 public static void EnsureHelper()
 {
     if (null == (object)instance)
     {
         WaitOneExtension.isWebPlayer = Application.isWebPlayer;
         instance = FindObjectOfType(typeof(UnityThreadHelper)) as UnityThreadHelper;
         if (null == (object)instance)
         {
             var go = new GameObject("[UnityThreadHelper]");
             go.hideFlags = HideFlags.NotEditable | HideFlags.HideInHierarchy | HideFlags.HideInInspector;
             instance = go.AddComponent<UnityThreadHelper>();
             instance.EnsureHelperInstance();
         }
     }
 }
 public static void EnsureHelper()
 {
     if (null == (object)instance)
     {
         WaitOneExtension.isWebPlayer = Application.isWebPlayer;
         instance = FindObjectOfType(typeof(UnityThreadHelper)) as UnityThreadHelper;
         if (null == (object)instance)
         {
             var go = new GameObject("[UnityThreadHelper]");
             go.hideFlags = HideFlags.NotEditable | HideFlags.HideInHierarchy | HideFlags.HideInInspector;
             instance     = go.AddComponent <UnityThreadHelper>();
             instance.EnsureHelperInstance();
         }
     }
 }
    // PUBLIC METHODS

    public void ConnectVirtualControllerToGame(VirtualControllerHandler virtualControllerHandler)
    {
        this.virtualControllerHandler = virtualControllerHandler;

        UnityThreadHelper.Dispatcher.Dispatch(() => {
            listener = SocketHelper.CreateUDPServer(port, (endPoint, receivedBytes) =>
            {
                HandleGameCommand(receivedBytes);
            });
            UnityThreadHelper.CreateThread(() =>
            {
                IsVirtualControllerAlive();
            });
        });
    }
    void OnDestroy()
    {
        foreach (var thread in registeredThreads)
            thread.Dispose();

        if (dispatcher != null)
            dispatcher.Dispose();
        dispatcher = null;

        if (taskDistributor != null)
            taskDistributor.Dispose();
        taskDistributor = null;

        if (instance == this)
            instance = null;
    }