Exemplo n.º 1
0
        public string Login(string username, string password)
        {
            string        json     = SocketController.Post(DiscordURL.Login, new LoginObject(username, password));
            LoginResponse response = JsonConvert.DeserializeObject <LoginResponse>(json);

            return(response.Token);
        }
Exemplo n.º 2
0
 private void Awake()
 {
     if (Instance == null)
     {
         Instance = this;
     }
 }
Exemplo n.º 3
0
    /// <summary>
    /// 在刚好接收完一个完整的协议的时候调用,构造一个完整的协议包
    /// </summary>
    public void CreatePacketFromBuffer()
    {
        try
        {
            int bodyLen = BodyLength;

            int    protoCode = ProtoCode;
            object decoder   = ProtoMapper.GetProtoDecoder(protoCode);
            if (decoder != null)
            {
                byte[] dataBytes = new byte[bodyLen - ProtoCodeLength]; //协议体等于总的协议体长度减去协议号字节
                Array.Copy(protobuffBytes, Header_Length + ProtoCodeLength, dataBytes, 0, dataBytes.Length);
                Debug.Log("Content :" + SocketController.ByteArrayToStr(dataBytes));
                System.IO.MemoryStream stream_output = new System.IO.MemoryStream(dataBytes);

                RuntimeTypeModel.Default.Deserialize(stream_output, decoder, decoder.GetType());

                ProtoPacketQueueManager.AddPacket(decoder);
                //用队列在帧更新的时候处理协议,是因为有可能是在多线程下通信,而有些操作是只能在主线程执行
            }
        }
        catch (System.Exception ex)
        {
            Debug.LogError("协议包创建出错:" + ex.Message + ex.StackTrace);
        }
    }
Exemplo n.º 4
0
        /// <summary>
        /// 连接Rmtp服务
        /// </summary>
        /// <param name="pIp">Rmtp目标IP</param>
        /// <param name="pPort">端口号</param>
        public void ConnectRmtpService(RmtpCommand pCmd)
        {
            string pIp   = ConfigurationManager.AppSettings["IP"];
            int    pPort = int.Parse(ConfigurationManager.AppSettings["Port"]);

            if (_rmtpControler != null && _rmtpControler.IsConnected)
            {
                return;
            }

            if (_rmtpDataFrameCache != null)
            {
                _rmtpDataFrameCache.ReceiveDataFrame -= OnReceiveDataFrame;
                _rmtpDataFrameCache = null;
            }

            _rmtpDataFrameCache = new RmtpDataFrameCache(pCmd);
            _rmtpDataFrameCache.ReceiveDataFrame += OnReceiveDataFrame;

            if (_rmtpControler != null)
            {
                _rmtpControler.Close();
                _rmtpControler.SocketConnected -= OnRmtpConnected;
                _rmtpControler.SocketError     -= OnRmtpError;
                _rmtpControler = null;
            }

            _rmtpControler = new SocketController(pIp, pPort, _rmtpDataFrameCache);
            _rmtpControler.SocketConnected += OnRmtpConnected;
            _rmtpControler.SocketError     += OnRmtpError;

            _rmtpControler.Connect();
        }
Exemplo n.º 5
0
        public static void Main(string[] args)
        {
            FileReader       __fileReader = new FileReader();
            SocketController __server     = new SocketController();

            SocketInitializationData __socketData = __fileReader.GetSocketInitializationData();

            __server.Initialize(__socketData);
            __server.StartSocket(delegate
            {
                Console.WriteLine("SERVER ON");
                __server.StartAcceptTcpClientThread(delegate
                {
                    Console.WriteLine("ALL CLIENTS OK");
                    __server.StartWaitClientsStreamThread(delegate
                    {
                        Console.WriteLine("ALL DATA RECEIVED");
                    });
                });
            }, delegate
            {
                Console.WriteLine("DEU RUIM");
            });
            while (true)
            {
            }
        }
Exemplo n.º 6
0
    void Start()
    {
        Instance = this;
        io       = FindObjectOfType <SocketIOController>();

        io.On("connect", e =>
        {
            //We just connected to the socket server
            Debug.Log("Connected");
            io.Emit("vieweronline");
        });

        io.On("reset", e =>
        {
            SceneManager.LoadScene(0);
        });

        io.On("enroll", e =>
        {
            ScreenDetector.gameObject.SetActive(true);
            ScreenDetector.EnrollNewScreen(e);
        });

        io.Connect();
    }
        public bool Start(out string error)
        {
            if (!SocketController.Start(out error))
            {
                return(false);
            }

            if (!ConnectionManager.Start(out error))
            {
                Log(error);
                return(false);
            }

            if (!Terrain.Start(out error))
            {
                Log(error);
                return(false);
            }
            //Run all
            foreach (var thread in updateThreads)
            {
                thread.Start(thread);
            }

            return(true);
        }
Exemplo n.º 8
0
        public async Task <bool> Connect()
        {
            bool connected = await SocketController.Connect("wss://gateway.discord.gg/?v=6&encoding=json");

            SocketListener.Listen();
            return(connected);
        }
Exemplo n.º 9
0
    public void populate(List <string> socketList, SocketController sockControl)
    {
        Debug.Log("POPULATING BOOK");
        int i = 0;

        txt1.text = "____________________________\n\n";
        txt2.text = "____________________________\n\n";
        Text outputTxt;

        foreach (string sckt in socketList)
        {
            if (i < (int)(socketList.Count / 2))
            {
                outputTxt = txt1;
            }
            else
            {
                outputTxt = txt2;
            }
            outputTxt.text += sckt + ":  \n";
            foreach (string name in sockControl.getNames(sckt))
            {
                outputTxt.text += "\t" + name + "\n";
            }
            outputTxt.text += "____________________________\n\n";
            i++;
        }
    }
Exemplo n.º 10
0
 /// <summary>
 /// Called when the user press to logout
 /// todo: Move from here because login does not have this option only in the next scenes
 /// </summary>
 protected void Logout()
 {
     if (SocketController.IsConnected())
     {
         Debug.Log("Requesting to logout..");
         SocketController.Send(NetworkInstructions.LOGOUT_REQUEST, null);
     }
 }
Exemplo n.º 11
0
 public bool Beat()
 {
     SocketController.Send(new Heartbeat());
     //Payload response = SocketController.Receive();
     //Console.WriteLine(response);
     return(true);
     //return response.Opcode == (int)Opcodes.HeartbeatACK;
 }
Exemplo n.º 12
0
        public Object execute(TransferObject to)
        {
            Object resultObject = null;

            resultObject = SocketController.execute(to);

            return(resultObject);
        }
Exemplo n.º 13
0
 /// <summary>
 /// TODO Soon
 /// </summary>
 protected void OnApplicationQuit()
 {
     //Shutdown the socket
     if (SocketController.GetSocketClient() != null && SocketController.GetSocketClient().Client.Connected)
     {
         Debug.Log("Requesting the socket to get lose");
         SocketController.GetSocketClient().Disconnect();
     }
 }
Exemplo n.º 14
0
    protected void Awake()
    {
        //Bind it
        SocketController.BindEvent(MsgType.Disconnect, OnDisconnect);


        //Load the resources here but soon move it to the loading thing
        //GameData.Initialize();
    }
Exemplo n.º 15
0
 void Start()
 {
     socket_controller_ = new SocketController();
     socket_controller_.Start();
     socket_controller_.game_manager_ = this;
     Time.timeScale          = 0f;
     game_over_text_.enabled = false;
     won_text_.enabled       = false;
 }
Exemplo n.º 16
0
 private void initParam()
 {
     dicCancelled   = new Dictionary <string, Ticket>();
     dicWaitting    = new Dictionary <string, Ticket>();
     dicServing     = new Dictionary <string, Ticket>();
     socController  = new SocketController();
     dicAllCounters = new Dictionary <string, Counter>();
     dicAllServices = new Dictionary <string, Service>();
 }
Exemplo n.º 17
0
 /// <summary>
 /// Called then the <see cref="SecureSocket"/> connects to the remote host.
 /// </summary>
 /// <param name="ar">An <see cref="IAsyncResult"/> instance.</param>
 private void OnConnect(IAsyncResult ar)
 {
     try {
         base.EndConnect(ar);
         m_Controller = new SocketController(this, base.InternalSocket, m_Options);
     } catch (Exception e) {
         m_ConnectResult.AsyncException = e;
     }
     m_ConnectResult.Notify();
 }
Exemplo n.º 18
0
 void Start()
 {
     game   = GameControllerServer.instant;
     socket = SocketController.instant;
     socket.On("JOIN", OnUserJoin);
     socket.On("LEAVE", OnUserLeave);
     socket.On("USERS", OnUsers);
     socket.OnEvent("LOOKAT", OnUserLook);
     socket.OnConnectHandler = ConnectToServer;
 }
 void Awake()
 {
     if (instance == null)
     {
         instance = this;
     }
     else if (instance != this)
     {
         Destroy(instance);
     }
     DontDestroyOnLoad(instance);
 }
Exemplo n.º 20
0
 private void Awake()
 {
     if (instance == null)
     {
         instance = this;
         DontDestroyOnLoad(gameObject);
     }
     else
     {
         Destroy(gameObject);
     }
 }
Exemplo n.º 21
0
    /// <summary>
    /// Enables the login panel and binds
    /// </summary>
    private void ShowLoginPanel()
    {
        //Show the UI
        LoginPanel.SetActive(true);

        //Bind login opcodes events
        SocketController.BindEvent(NetworkInstructions.LOGIN_FAIL, OnLoginFail);
        SocketController.BindEvent(NetworkInstructions.LOGIN_SUCCESS, OnLoginSuccess);

        //Destroy the loading box
        Destroy(GameObject.Find("LoadingBox"));
    }
Exemplo n.º 22
0
        public void Index_WhenCalled_ShouldNotReturnNull()
        {
            // Arrange
            SocketController controller = new SocketController(_userManager, _roomRepository, _socketRepository,
                                                               _timeTaskRepository, _authorizationService, _mqttAppClient, _mapper);

            // Act
            ViewResult viewResult = controller.Index() as ViewResult;

            // Assert
            Assert.NotNull(viewResult);
        }
Exemplo n.º 23
0
        public void Delete_WhenCalledWithIntParameter_ShouldNotReturnNull()
        {
            // Arrange
            SocketController controller = new SocketController(_userManager, _roomRepository, _socketRepository,
                                                               _timeTaskRepository, _authorizationService, _mqttAppClient, _mapper);

            // Act
            ViewResult viewResult = controller.Delete(1).GetAwaiter().GetResult() as ViewResult;

            // Assert
            Assert.NotNull(viewResult);
        }
Exemplo n.º 24
0
    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }

        PopUp.OnClosePopUp += OnQuitMatch;
    }
Exemplo n.º 25
0
        public bool Update(out string error)
        {
            error = null;

            if (!SocketController.Update(out error))
            {
                return(false);
            }

            /*if (!Terrain.Update(out error))
             *  return false;*/

            return(true);
        }
Exemplo n.º 26
0
    private void LoadScenesAndStart()
    {
        _globalController = GlobalController.Instance;

        //SceneLoader.Instance.AddScene(States.State.HOME, "Prefabs/Scenes/Onboarding", ObjectHolder.Instance.BottomCanvas, true, false, true);
        //SceneLoader.Instance.AddScene(States.State.EVENT, "Prefabs/Scenes/RegisterPhone", ObjectHolder.Instance.BottomCanvas, true, false, true);

        SceneLoader.Instance.Load();


        _startState = States.State.HOME;

        _socketController = SocketController.Instance;
        SplashObject.SetActive(false);
    }
Exemplo n.º 27
0
 /// <summary>
 /// Changes the security protocol. This method can only be used to 'upgrade' a connection from no-security to either SSL or TLS.
 /// </summary>
 /// <param name="options">The new <see cref="SecurityOptions"/> parameters.</param>
 /// <exception cref="SecurityException">An error occurs while changing the security protocol.</exception>
 /// <remarks>
 /// Programs should only call this method if there is no active <see cref="Connect"/>, <see cref="Accept"/>, <see cref="Send"/> or <see cref="Receive"/>!
 /// </remarks>
 public void ChangeSecurityProtocol(SecurityOptions options)
 {
     if (options == null)
     {
         throw new ArgumentNullException();
     }
     if (m_Options != null && m_Options.Protocol != SecureProtocol.None)
     {
         throw new ArgumentException("Only changing from a normal connection to a secure connection is supported.");
     }
     if (base.ProtocolType != ProtocolType.Tcp && options.Protocol != SecureProtocol.None)
     {
         throw new SecurityException("Security protocols require underlying TCP connections!");
     }
     // check SecurityOptions structure
     if (options.Protocol != SecureProtocol.None)
     {
         if (options.Entity == ConnectionEnd.Server && options.Certificate == null)
         {
             throw new ArgumentException("The certificate cannot be set to a null reference when creating a server socket.");
         }
         if (options.Certificate != null && !options.Certificate.HasPrivateKey())
         {
             throw new ArgumentException("If a certificate is specified, it must have a private key.");
         }
         if (((int)options.AllowedAlgorithms & (int)SslAlgorithms.NULL_COMPRESSION) == 0)
         {
             throw new ArgumentException("The allowed algorithms field must contain at least one compression algorithm.");
         }
         if (((int)options.AllowedAlgorithms ^ (int)SslAlgorithms.NULL_COMPRESSION) == 0)
         {
             throw new ArgumentException("The allowed algorithms field must contain at least one cipher suite.");
         }
         if (options.VerificationType == CredentialVerification.Manual && options.Verifier == null)
         {
             throw new ArgumentException("A CertVerifyEventHandler is required when using manual certificate verification.");
         }
     }
     m_Options = (SecurityOptions)options.Clone();
     if (options.Protocol != SecureProtocol.None)
     {
         if (this.Connected)
         {
             m_Controller = new SocketController(this, base.InternalSocket, options);
         }
     }
 }
Exemplo n.º 28
0
    /// <summary>
    /// Called when the server returns Login Success opcode
    /// </summary>
    /// <param name="netMsg"></param>
    protected void OnLoginSuccess(NetworkMessage netMsg)
    {
        UnityMainThreadDispatcher.Instance().Enqueue(() =>
        {
            LoginPanel.SetActive(false);
            if (GameObject.Find("LoadingBox") != null)
            {
                Destroy(GameObject.Find("LoadingBox"));
            }

            //Create a spinner
            var spin  = Instantiate(Resources.Load <GameObject>("Prefabs/Modals/LoadingBox"), UI.transform) as GameObject;
            spin.name = "LoadingBox";
            spin.transform.Find("Text").GetComponent <Text>().text = "Loading Profile..";

            //Read profileData
            var profileData = netMsg.ReadMessage <ProfileData>();


            //We make observer for WhenData arrives in order to define dynamiclly when loading or loaded is done
            spin.transform.Find("Text").GetComponent <Text>().text = "Loading Cards..";
            SocketController.Send(NetworkInstructions.PLAYER_CARDS_REQUEST, null);

            //Save the username and pwd if the remmeber is set true
            if (PlayerPrefs.GetInt("login_remmeber") == 1)
            {
                PlayerPrefs.SetString("login_username", usrField.text);
                PlayerPrefs.SetString("login_password", pwdField.text);
                Debug.Log("Remmeber saved");
            }

            //Unbind the login handlers since we're going to load the next scene
            SocketController.UnbindEvent(NetworkInstructions.LOGIN_FAIL);
            SocketController.UnbindEvent(NetworkInstructions.LOGIN_REQUEST);
            SocketController.UnbindEvent(NetworkInstructions.LOGIN_SUCCESS);

            //Wipe notifier list if it gives problems trying to notify here
            SocketController.UnbindEvent(NetworkInstructions.ServerOffline);

            //Load next scene
            SceneManager.LoadSceneAsync("MainMenu");
        });
    }
Exemplo n.º 29
0
        public void Listen()
        {
            IsListening = true;

            new Thread(async() =>
            {
                while (IsListening)
                {
                    if (SocketController.IsConnected)
                    {
                        Payload payload = await SocketController.Receive();
                        if (payload != null)
                        {
                            PayloadReceived(payload);
                        }
                    }
                }
            }).Start();
        }
Exemplo n.º 30
0
        public bool Stop(out string error)
        {
            if (!SocketController.Stop(out error))
            {
                return(false);
            }
            //stop all
            foreach (var thread in updateThreads)
            {
                thread.Stop();
            }

            //join all
            foreach (var thread in updateThreads)
            {
                thread.Join();
            }

            return(Terrain.Stop(out error));
        }