Пример #1
0
        public void MessageReceived(object sender, MessageReceivedEventArgs args)
        {
            MemoryStream stream = new MemoryStream(args.Data);
            BinaryReader reader = new BinaryReader(stream);

            while (stream.Position < reader.BaseStream.Length)
            {
                byte           packetType = reader.ReadByte();
                GamePacketType packet     = (GamePacketType)packetType;
                GamePacketsImpl.ExecutePacket(packet, manager.ClientsManager.clients[args.IpPort], reader);
            }
        }
Пример #2
0
    async void TryConnect()
    {
        string ip = useRemoteIp ? remoteIp : this.ip;

        websocket = new WebSocket(ip);
        Debug.Log("Connect to: " + ip);
        websocket.OnOpen += () =>
        {
            connected = true;
            if (routine != null)
            {
                StopCoroutine(routine);
            }
            Debug.Log("Connection open!");
            UnityMainThreadDispatcher.Instance().Enqueue(() =>
            {
                SceneManager.LoadScene(1);
            });
        };

        websocket.OnError += (e) =>
        {
            Debug.Log("Error! " + e);
        };

        websocket.OnClose += (e) =>
        {
            connected = false;

            Debug.Log("Connection closed!");
            UnityMainThreadDispatcher.Instance().Enqueue(() =>
            {
                if (SceneManager.GetActiveScene().buildIndex == 1)
                {
                    Destroy(gameObject);
                    SceneManager.LoadScene(0);
                }
                else
                {
                    //Destroy(gameObject);
                    //Instantiate(connectionPrefab);
                }
            });
        };

        websocket.OnMessage += (bytes) =>
        {
            // Reading a plain text message
            // var message = System.Text.Encoding.UTF8.GetString(bytes);
            // Debug.Log("OnMessage! " + message);

            UnityMainThreadDispatcher.Instance().Enqueue(() =>
            {
                MemoryStream stream = new MemoryStream(bytes);
                BinaryReader reader = new BinaryReader(stream);

                while (stream.Position < reader.BaseStream.Length)
                {
                    byte packetType       = reader.ReadByte();
                    GamePacketType packet = (GamePacketType)packetType;

                    GamePacketsImpl.ExecutePacket(packet, reader);
                }
            });
        };

        //routine = StartCoroutine(ReconnectionRoutine());
        await websocket.Connect();
    }