Recv() public méthode

public Recv ( ) : byte[]
Résultat byte[]
Exemple #1
0
    IEnumerator ConnectToWebSocket(string ws)
    {
        webSocket = new WebSocket(new Uri(ws));
        yield return(StartCoroutine(webSocket.Connect()));

        while (true)
        {
            byte[] replyBytes = webSocket.Recv();
            if (replyBytes != null)
            {
                string reply     = Encoding.ASCII.GetString(replyBytes);
                var    replyType = JsonConvert.DeserializeObject <WsForm>(reply).Type;
                if (WebsocketActions.ContainsKey(replyType))
                {
                    WebsocketActions[replyType](reply);
                }
            }
            if (webSocket.error != null)
            {
                Debug.LogError("Error: " + webSocket.error);
                break;
            }
            yield return(0);
        }
        webSocket.Close();
    }
Exemple #2
0
    public IEnumerator threadReceiveMSG()
    {
        while (connected)
        {
            try {
                byte[] data = w_socket.Recv();
                if (data != null)
                {
                    sbyte[] sdata = new sbyte[data.Length];
                    for (int i = 0; i < data.Length; i++)
                    {
                        if (data[0] > 127)
                        {
                            sdata[0] = (sbyte)(data[0] - 256);
                        }
                        sdata[i] = (sbyte)data[i];
                    }
                    //				string decodedString = Encoding.UTF8.GetString(data);
                    //				byte[] bytes = Encoding.ASCII.GetBytes(decodedString);

                    processMsgFromData(sdata, sdata.Length);
                }
            } catch (Exception e) {
                Debug.LogException(e);
            }
            if (w_socket.error != null)
            {
                messageHandler.onDisconnected();
                break;
            }
            yield return(0);
        }
        cleanNetwork();
    }
        void ReceiveWebSocketData()
        {
            var recvData = WebSocket.Recv();

            if (string.IsNullOrEmpty(recvData))
            {
                return;
            }

            if (recvData == Packet.ProbeAnswer)
            {
                IsProbed = true;
                Debug.LogFormat("socket.io => {0} probed~", WebSocket.Url.ToString());
            }
            else if (recvData == Packet.Pong)
            {
                Debug.LogFormat("socket.io => {0} pong~", WebSocket.Url.ToString());
            }
            else
            {
                if (_onRecv != null)
                {
                    _onRecv.OnNext(recvData);
                }
            }
        }
Exemple #4
0
    public void Update()
    {
        if (!init || error)
        {
            return;
        }

        byte[] data = socket.Recv();

        if (data == null || data.Length == 0)
        {
            return;
        }

        cache.AddRange(data);

        if (!isRead)
        {
            isRead = true;
            Read();
        }

        if (socket.error != null)
        {
            Debug.Log(socket.error);
            error = true;
        }
    }
Exemple #5
0
        public void Play()
        {
            var uri = new Uri(Server + "?user="******"Something strange is happening on the server... Response:\n{0}", response);
                        ShouldExit = true;
                    }
                    else
                    {
                        var boardString = response.Substring(ResponsePrefix.Length);

                        var action = DoMove(new GameBoard(boardString));

                        socket.Send(action);
                    }
                }
            }
        }
    public IEnumerator ReadPump()
    {
        // Loop forever, untill an error occurs
        while (_ws != null && _ws.error == null && _ws.IsConnected())
        {
            // Read all incoming messages
            while (_ws != null && _ws.error == null && _ws.IsConnected())
            {
                // Read bytes
                byte[] incoming = _ws.Recv();
                if (incoming != null && _ws.error == null)
                {
                    // Convert for easy reading
                    CodedInputStream input = new CodedInputStream(incoming);

                    // Fetch message type
                    MessageType msgType = (MessageType)input.ReadUInt32();

                    // Handle message if registered
                    if (_msgMap.ContainsKey(msgType))
                    {
                        // DEBUG
                        NetworkManager.Log("Message of type " + msgType.ToString());

                        // Call the function that has to handle this message
                        _msgMap[msgType](input);
                    }
                    else
                    {
                        Debug.LogError("Unknown message type " + msgType);
                    }
                }
                else
                {
                    // The last Recv returned nothing, so we have no more messages to process this frame
                    break;
                }
            }

            // Did any errors arise?
            if (_ws.error != null)
            {
                Debug.LogError("WebSocket Error: " + _ws.error);
                break;
            }

            // Wait untill next frame
            yield return(0);
        }

        // We are disconnected, cleanup
        for (int i = 0; i < _disconnectHandlers.Count; i++)
        {
            _disconnectHandlers[i]();
        }
        _disconnectHandlers.Clear();
        _ws = null;
    }
Exemple #7
0
 public object ReceiveMessage()
 {
     byte[] recv_msg = web_socket.Recv();
     if (recv_msg != null)
     {
         MemoryStream memory_stream = new MemoryStream(recv_msg);
         down_msg     rec_message   = Serializer.Deserialize <down_msg>(memory_stream);
         return(rec_message);
     }
     return(null);
 }
Exemple #8
0
    void ListenServerMessage()
    {
        string replyStr = ws.RecvString();

        if (replyStr != null)
        {
            //Debug.Log("raw replyStr=" + replyStr);
            strMessagesFromServer.Enqueue(replyStr);
        }

        byte[] replyBytes = ws.Recv();
        if (replyBytes != null)
        {
            //Debug.Log("raw replyBytes=" + replyBytes.ToString());
            bytesMessagesFromServer.Enqueue(replyBytes);
        }
    }
Exemple #9
0
        void ReceiveWebSocketData()
        {
            var recvData = WebSocket.Recv();

            if (string.IsNullOrEmpty(recvData))
            {
                return;
            }

            if (recvData == Packet.ProbeAnswer)
            {
                IsProbed = true;
                Debug.LogFormat("socket.io => {0} probed~", WebSocket.Url.ToString());
            }
            else if (recvData == Packet.Pong)
            {
                // Debug.Log("pong.recvData=" + recvData.ToString());
                Debug.LogFormat("socket.io => {0} pong~", WebSocket.Url.ToString());
            }
            // else if (recvData[0] == Packet.Pong[0]) {
            //     Debug.Log("pong(custom).recvData=" + recvData.ToString());

            //     string dataString = recvData.Substring(1, recvData.Length-1);
            //     Debug.Log("pong(custom).dataString=" + dataString.ToString());

            //     Debug.LogFormat("socket.io => {0} pong~ : time {1}", WebSocket.Url.ToString(), Time.time - this.pingStartTime);

            //     PongData pongData = JsonUtility.FromJson<PongData>(dataString);
            //     Debug.Log("pong(custom).pongData=" + pongData.ToString());

            //     // Client -> Server 도착 시간 = [(PingPong 도착 시간 - Ping 요청 시간) - (Pong Server 보낸시간 - Ping Server 도착시간)] * 0.5f
            //     float serverProcessSecTime = (float)pongData.serverProcessMsTime * 0.001f;
            //     this.clientToServerLatencySec = ((Time.time - this.pingStartTime) - serverProcessSecTime) * 0.5f;

            //     Debug.LogFormat("pong(custom).clientToServerLatencySec=" + this.clientToServerLatencySec.ToString());
            // }
            else
            {
                if (_onRecv != null)
                {
                    // Debug.Log("data.recvData=" + recvData.ToString());
                    _onRecv.OnNext(recvData);
                }
            }
        }
Exemple #10
0
    public void Update()
    {
        if (socket != null)
        {
            byte[] data = socket.Recv();
            if (data == null || data.Length == 0)
            {
                return;
            }

            using (MessageBuffer buffer = MessageBuffer.Create(data.Length))
            {
                Buffer.BlockCopy(data, 0, buffer.Buffer, 0, data.Length);
                buffer.Count = data.Length;
                HandleMessageReceived(buffer, SendMode.Reliable);
            }
        }
    }
Exemple #11
0
        void Update()
        {
            if (IsConnect())
            {
                byte[] bts = _socket.Recv();

                if (bts != null && bts.Length > 0)
                {
                    _dataBuffer.Seek(0, SeekOrigin.End);
                    _dataBuffer.WriteBytes(bts, 0, bts.Length);
                    _dataBuffer.Seek(0, SeekOrigin.Begin);
                }

                if (_dataBuffer.RemainLen() > NetEncoder.HEAD_LEN)
                {
                    int cmd, datalen;
                    NetEncoder.OnRecvHead(_dataBuffer, out cmd, out datalen);

                    if (_dataBuffer.RemainLen() >= datalen)
                    {
                        NetBuffer msgbuf = new NetBuffer();
                        msgbuf.WriteBytes(_dataBuffer.ReadBytes(datalen));
                        msgbuf.Seek(0, SeekOrigin.Begin);
                        _dataBuffer.ResetRemain();
                        int len = msgbuf.GetLength();

                        byte[] data;
                        data = NetEncoder.OnRecvData(msgbuf.ReadBytes(len));

                        if (cmd == 0)
                        {
                            onConnect?.Invoke(true, "");
                        }
                        onReceive?.Invoke(cmd, data);
                    }
                    else
                    {
                        _dataBuffer.Seek(0, SeekOrigin.Begin);
                        // _dataBuffer.ResetRemain();
                    }
                }
            }
        }
Exemple #12
0
    private IEnumerator ReceiveDataWSX()
    {
        WebSocket w = new WebSocket(new Uri(url));

        yield return(StartCoroutine(w.Connect()));

        while (true)
        {
            byte [] reply = w.Recv();              // non blocking
            if (reply != null)
            {
                string s = Encoding.UTF8.GetString(reply, 0, 4);
                OnMessage(s);
            }
            if (w.error != null)
            {
                Debug.Log("Error: " + w.error);
                break;
            }
            yield return(0);
        }
        w.Close();
    }
    // Use this for initialization
    IEnumerator Start()
    {
        omicronManager = GetComponent <OmicronManager>();

        ws = new WebSocket(new System.Uri("ws://" + sage2Server + ":" + sage2OmicronPort));
        yield return(StartCoroutine(ws.Connect()));

        while (true)
        {
            byte[] reply = ws.Recv();
            if (reply != null)
            {
                omicronManager.AddEvent(omicronConnector.OmicronConnectorClient.ByteArrayToEventData(reply));
            }
            if (ws.error != null)
            {
                Debug.LogError("Error: " + ws.error);
                break;
            }
            yield return(0);
        }
        ws.Close();
    }
        void Update()
        {
            var err = WebSocket.GetLastError();

            if (err != string.Empty)
            {
                _onRecv.OnError(new WebSocketErrorException(err));
                _onRecv.Dispose();
                _onRecv    = null;
                IsProbed   = false;
                IsUpgraded = false;
            }

            if (IsConnected)
            {
                var recvData = WebSocket.Recv();
                if (recvData != null)
                {
                    if (recvData == Packet.ProbeAnswer)
                    {
                        IsProbed = true;
                        Debug.LogFormat("socket.io => {0} probed~", WebSocket.Url.ToString());
                    }
                    else if (recvData == Packet.Pong)
                    {
                        Debug.LogFormat("socket.io => {0} pong~", WebSocket.Url.ToString());
                    }
                    else
                    {
                        if (_onRecv != null)
                        {
                            _onRecv.OnNext(recvData);
                        }
                    }
                }
            }
        }
Exemple #15
0
        public void Play()
        {
            string url = GetWebSocketUrl(this.ServerUrl);

            using (var socket = new WebSocket(new Uri(url)))
            {
                socket.Connect();

                while (!ShouldExit)
                {
                    var response = socket.Recv();

                    if (!response.StartsWith(ResponsePrefix))
                    {
                        Console.WriteLine("Something strange is happening on the server... Response:\n{0}", response);
                        ShouldExit = true;
                    }
                    else
                    {
                        var boardString = response.Substring(ResponsePrefix.Length);
                        var board       = new Board(boardString);

                        //Just print current state (gameBoard) to console
                        Console.Clear();
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine(board.ToString());

                        var action = Get(board);

                        Console.WriteLine("Answer: " + action);
                        Console.SetCursorPosition(0, 0);

                        socket.Send(action.ToString());
                    }
                }
            }
        }
        IEnumerator BeginLoop()
        {
            var url = ServerURL;

            Debug.Log($"connect to {url}");
            ws = new WebSocket(new Uri(url));
            yield return(StartCoroutine(ws.Connect()));

            if (ws.error != null)
            {
                _error.OnNext(ws.error);
                yield break;
            }

            // connection success
            readySubject.OnNext(true);
            SendImmediate(new ConnectPacket());

            while (ws != null)
            {
                byte[] bytes = null;
                while (ws != null && bytes == null)
                {
                    if (ws.error != null)
                    {
                        _error.OnNext(ws.error);
                    }

                    bytes = ws.Recv();
                    yield return(null);
                }

                var now = TimeUtils.NowTimestamp;
                bandwidth.AddReceived(bytes.Length, now);
                dispatcher.Dispatch(bytes, 0);
            }
        }
    IEnumerator Start()
    {
        ws = new WebSocket(new Uri("ws://127.0.0.1:8001/counter"));
        yield return(StartCoroutine(ws.Connect()));

        int counter = 1;

        while (true)
        {
            SendCounter(ws, counter);
            if (ws.error != null)
            {
                Debug.LogError($"Error: " + ws.error);
                break;
            }

            byte[] bytes = null;
            while (bytes == null)
            {
                bytes = ws.Recv();
                yield return(null);
            }

            counter = RecvCounter(bytes);
            if (ws.error != null)
            {
                Debug.LogError($"Error: " + ws.error);
                break;
            }

            yield return(new WaitForSeconds(1));
        }

        ws.Close();
        ws = null;
    }
Exemple #18
0
 private void RecvFromSocket()
 {
     byte[] bytes = _socket.Recv();
     if (bytes != null)
     {
         Buffer.BlockCopy(bytes, 0, _headBuffer, 0, 4);
         Int32 value   = (Int32)BitConverter.ToUInt32(_headBuffer, 0);
         Int32 _msgLen = (Int32)IPAddress.NetworkToHostOrder(value) - 1;
         _bodyBuffer = new byte[_msgLen];
         Buffer.BlockCopy(bytes, 5, _bodyBuffer, 0, _msgLen);
         byte      isZip     = bytes[4];
         ByteArray byteArray = NetMgr.GetInstance().byteArrayPool.Pop();
         if (isZip == 1)
         {
             byte[] unZipBuff = Ionic.Zlib.ZlibStream.UncompressBuffer(_bodyBuffer);
             byteArray.CreateFromBuff(unZipBuff, false);
         }
         else
         {
             byteArray.CreateFromBuff(_bodyBuffer, false);
         }
         this.recvQueue.Enqueue(byteArray);
     }
 }
Exemple #19
0
        IEnumerator Start()
        {
            _packetHandler = new PacketHandler();
            _socket        = new WebSocket(new Uri("ws://" + GameSession.ServerUrl + "/game"));
            ReadWriteBuffer buffer        = new ReadWriteBuffer(16777216);
            bool            handshakeSent = false;

            PacketHandler.LoginPacketReceivedEvent += OnSetCompressionPacket;
            PacketHandler.PlayPacketReceivedEvent  += OnPlayerAbilitiesPacket;
            PacketHandler.PlayPacketReceivedEvent  += OnKeepAlivePacket;

            int   size            = -1;
            float lastWSKeepAlive = Time.time;

            yield return(StartCoroutine(_socket.Connect()));

            while (true)
            {
                // Send "keep alive" to bridge/webcraft server
                if (Time.time - lastWSKeepAlive > 0.5f)
                {
                    lastWSKeepAlive = Time.time;
                    _socket.Send(new byte[0]);
                }

                byte[] inByte = _socket.Recv();

                if (inByte != null && inByte.Length > 0)
                {
                    buffer.Write(inByte);
                }

                while (buffer.Count > 4 && size == -1)
                {
                    size = buffer.ReadVarInt();
                }


                if (size != -1 && size <= buffer.Count)
                {
                    MemoryStream packet = new MemoryStream(buffer.Read(size));
                    size = -1;
                    StartCoroutine(ReadPacket(packet));
                }

                if (!handshakeSent)
                {
                    new HandshakePacket(340, "", 0, HandshakePacket.States.Login)
                    .Send(this);

                    SendPacket(new MemoryStream()
                               .WriteString(GameSession.Login), 0x00, false);
                    handshakeSent = true;
                }

                if (_socket.error != null)
                {
                    Debug.LogError("Error: " + _socket.error);
                    break;
                }

                if (buffer.Count <= 4)
                {
                    yield return(new PriorityYieldInstruction(PriorityYieldInstruction.Priority.High));
                }
            }
            _socket.Close();
        }
    // Use this for initialization
    IEnumerator Start () {
		w = new WebSocket(new Uri("ws://ec2-54-213-60-9.us-west-2.compute.amazonaws.com:16248"));
        w.OnError += OnError;
        w.OnLogMessage += OnLogMessage;
        Debug.Log("Trying to connect");
        yield return StartCoroutine(w.Connect());
        Debug.Log(w.isConnected ? "Connected!" : "Couldn't connect");
		while (true) {
            if (w.lastError != null)
                break;
            var reply = w.Recv();
            if (reply != null) {
                //var stringData = "[";
                //for (var i = 0; i < reply.Length; ++i)
                //{
                //    if (i % 4 == 0)
                //        stringData += "\n";
                //    var c = reply[i];
                //    stringData += " " + c.ToString("000");
                //}
                //stringData += " ]";
                //Debug.Log("Received from the server: " + stringData);
                uint spec = BitConverter.ToUInt32(reply, 0);
                switch (spec) {
                    case specInitialize:
                        {
                            uint id = BitConverter.ToUInt32(reply, 4);
                            player.id = id;
                            uint otherPlayerCount = BitConverter.ToUInt32(reply, 8);
                            int byteIndex = 12;
                            for (int i = 0; i < otherPlayerCount; ++i)
                            {
                                var other = new Player();
                                other.id = BitConverter.ToUInt32(reply, byteIndex);
                                other.name = Encoding.Unicode.GetString(reply, byteIndex + 4, nameLength);
                                float x = BitConverter.ToSingle(reply, byteIndex + nameLength + 4);
                                float y = BitConverter.ToSingle(reply, byteIndex + nameLength + 8);
                                float z = BitConverter.ToSingle(reply, byteIndex + nameLength + 12);
                                other.pos = new Vector3(x, y, z);
                                other.health = BitConverter.ToSingle(reply, byteIndex + nameLength + 16);
                                otherPlayers[other.id] = other;
                                byteIndex += 4 + nameLength + 16;
                            }
                            Debug.Log("Received ID: " + id + " and game start info.  There are " + otherPlayerCount + " other players.");
                            if (onGameInfoReceived != null)
                                onGameInfoReceived(id, otherPlayers);
                            break;
                        }
                    case specDisconnect:
                        {
                            uint id = BitConverter.ToUInt32(reply, 4);
                            Player other = null;
                            if (otherPlayers.TryGetValue(id, out other))
                            {
                                Debug.Log(other.name + " disconnected.");
                                if (onPlayerDisconnected != null)
                                    onPlayerDisconnected(other);
                            } else
                                Debug.Log("player" + id + " disconnected.");
                            otherPlayers.Remove(id);
                            break;
                        }
                    case specAnnounceConnect:
                        {
                            uint id = BitConverter.ToUInt32(reply, 4);
                            if (id == player.id)
                                break;
                            Player other = new Player();
                            other.id = id;
                            other.name = Encoding.Unicode.GetString(reply, 8, nameLength);
                            float x = BitConverter.ToSingle(reply, 8 + nameLength);
                            float y = BitConverter.ToSingle(reply, 12 + nameLength);
                            float z = BitConverter.ToSingle(reply, 16 + nameLength);
                            other.pos = new Vector3(x, y, z);
                            otherPlayers[id] = other;
                            Debug.Log(other.name + " has connected (id " + other.id + ", pos " + other.pos + ")");
                            if (onPlayerConnected != null)
                                onPlayerConnected(other);
                            break;
                        }
                    case specUpdatePosition:
                        {
                            uint id = BitConverter.ToUInt32(reply, 4);
                            float x = BitConverter.ToSingle(reply, 8);
                            float y = BitConverter.ToSingle(reply, 12);
                            float z = BitConverter.ToSingle(reply, 16);
                            var pos = new Vector3(x, y, z);
                            Player other = null;
                            if (player.id == id)
                                break;
                            if (otherPlayers.TryGetValue(id, out other)) {
                                //Debug.Log(other.name + " is now at position " + pos);
                                other.pos = pos;
                                if (onPlayerMoved != null)
                                    onPlayerMoved(other);
                            }
                            break;
                        }
                    case specMessage:
                        {
                            uint id = BitConverter.ToUInt32(reply, 4);
                            string message = Encoding.Unicode.GetString(reply, 8, reply.Length - 8);
                            string name = null;
                            if (id == player.id)
                                name = player.name;
                            if (name == null) {
                                Player other = null;
                                if (otherPlayers.TryGetValue(id, out other)) {
                                    name = other.name;
                                    if (onPlayerMessage != null)
                                        onPlayerMessage(other, message);
                                }
                            }
                            if (name != null)
                                Debug.Log(name + ": " + message);
                            else
                                Debug.Log("player" + id + ": " + message);
                            break;
                        }
                    case specHeartbeat:
                        {
                            SendHeartbeatResponse();
                            break;
                        }
                    case specUpdateHealth:
                        {
                            uint id = BitConverter.ToUInt32(reply, 4);
                            float health = BitConverter.ToSingle(reply, 8);
                            Player updatedPlayer = null;
                            if (id == player.id)
                            {
                                updatedPlayer = player;
                            } else
                            {
                                Player other = null;
                                if (otherPlayers.TryGetValue(id, out other))
                                {
                                    updatedPlayer = other;
                                }
                            }
                            if (updatedPlayer != null)
                            {
                                updatedPlayer.health = health;
                                if (onPlayerUpdateHealth != null)
                                    onPlayerUpdateHealth(updatedPlayer, health);
                            }
                            break;
                        }
                    case specUpdateState:
                        {
                            uint id = BitConverter.ToUInt32(reply, 4);
                            int stateSize = reply.Length - 8;
                            byte[] state = new byte[stateSize];
                            Buffer.BlockCopy(reply, 8, state, 0, stateSize);
                            Player updatedPlayer = null;
                            if (id == player.id) {
                                updatedPlayer = player;
                            } else {
                                Player other = null;
                                if (otherPlayers.TryGetValue(id, out other)) {
                                    updatedPlayer = other;
                                }
                            }
                            if (updatedPlayer != null) {
                                updatedPlayer.state = state;
                                if (onPlayerUpdateState != null)
                                    onPlayerUpdateState(updatedPlayer, state);
                            }
                            break;
                        }
                }
            } else {
                yield return 0;
            }
		}
		w.Close();
	}
Exemple #21
0
        void Update()
        {
            if (!string.IsNullOrEmpty(_socket.Error))
            {
                Debug.LogWarning(_socket.Error);
                Start();
                return;
            }

            Profiler.BeginSample("socket.recv");
            byte[] data = _socket.Recv();
            Profiler.EndSample();

            if (data == null || data.Length == 0)
            {
                return;
            }

            if (_state == ConnectionState.UNKNOWN)
            {
                _state = ConnectionState.CONNECTED;
            }

            if (data.Length < 4)
            {
                Debug.Log("partial message!");
                _storeAddPartial(data);
            }

            if (_partial_message != null)
            {
                Debug.Log("reconstructing partial message!");
                data             = ArrayUtil.sumArrays(_partial_message, data);
                _partial_message = null;
            }

            int messageLen = BitConverter.ToInt32(data, 0);
            int realLen    = data.Length - 5;

            if (realLen < messageLen)
            {
                _storeAddPartial(data);
                return;
            }
            else if (realLen > messageLen)
            {
                Debug.LogError("AHAHAH");
                return;
            }

            if (data[4] == DebugPackage.ID)
            {
                var dm = new DebugPackage(data);
                Debug.Log("debug message from: " + dm.sender + "::" + dm.message);
            }

            if (_state == ConnectionState.CONNECTED)
            {
                if (data[4] == Welcome.ID)
                {
                    _game.showWelcomeData(new Welcome(data));
                    _state = ConnectionState.WELCOMED;
                }
                else
                {
                    Debug.LogError("expected welcome, got :" + data[4].ToString() + " instead");
                    return;
                }
            }
            else if (_state == ConnectionState.AUTHORIZING)
            {
                if (data[4] == ResponseEnterWorld.ID)
                {
                    var res = new ResponseEnterWorld(data);
                    if (res.status == EnterWorldStatus.ENTER_SUCCESS)
                    {
                        Debug.Log("authorize success at world " + _lastWorldAttempt +
                                  " with name " + _lastNameAttempt + "::" + res.myId.ToString());
                        _state = ConnectionState.AUTHORIZED;
                        _game.rememberMe(_lastNameAttempt, res.myId, _lastWorldAttempt);
                    }
                    else
                    {
                        Debug.Log("authorize failed!");
                        _game.showWelcomeData();
                        _state = ConnectionState.WELCOMED;
                    }
                }
                else
                {
                    Debug.LogError("expected auth response or new seed, got :" + data[4].ToString() + " instead");
                    return;
                }
            }
            else if (_state == ConnectionState.AUTHORIZED)
            {
                if (data[4] == WorldData.ID)
                {
                    Debug.Log("world data received!");
                    var wData = new WorldData(data);
                    _game.initializeWorld(wData);
                    _state = ConnectionState.IN_WORLD;

                    _socket.Send(new DebugPackage(_game.myName, "привет друзья").encode());
                }
                else
                {
                    Debug.LogError("expected world data, got :" + data[4].ToString() + " instead");
                    return;
                }
            }
            else if (_state == ConnectionState.IN_WORLD)
            {
                if (data[4] == WorldSnapshot.ID)
                {
                    Profiler.BeginSample("recv.snapshot");
//                    Debug.Log("snapshot received!");
                    Profiler.BeginSample("unpack snapshot");
                    var snap = new WorldSnapshot(data);
                    Profiler.EndSample();

                    Profiler.BeginSample("decode snapshot");
                    var s = new byte[snap.snapshot.Length];
                    for (int i = 0; i < snap.snapshot.Length; i++)
                    {
                        s[i] = (byte.Parse(snap.snapshot[i].ToString()));
                    }
                    Profiler.EndSample();

                    Profiler.BeginSample("push snapshot");
                    _game.pushSnapshot(s);
                    Profiler.EndSample();
                    Profiler.EndSample();
                }
                else
                if (data[4] == NewSeed.ID)
                {
                    Debug.Log("new seed received ");
                    var seed = new NewSeed(data);
                    _game.pushSeed(seed.location, seed.owner);
                }
                else
                if (data[4] == SeedDestroyed.ID)
                {
                    var seedD = new SeedDestroyed(data);
                    Debug.Log("seed dest: " + seedD.location);
                    _game.destroySeed(seedD.location);
                }
                else
                if (data[4] == DeployBomb.ID)
                {
                    var enemy_bomb = new DeployBomb(data);
                    Debug.Log("enemy bomb: " + enemy_bomb.target);
                    _game.pushBomb(enemy_bomb.target);
                }
            }
        }
Exemple #22
0
    IEnumerator RemoteSocketLoad()
    {
        WebSocket w = new WebSocket(new Uri("ws://localhost:8001"));

        yield return(StartCoroutine(w.Connect()));

        int i = 0;

        while (true)
        {
            byte[] reply = w.Recv();
            if (reply != null)
            {
                string replyString = System.Text.Encoding.UTF8.GetString(reply, 0, reply.Length);
                if (replyString.Contains("START_OBJECT"))
                {
                    Debug.Log("Starting reading in object");
                    readingInObject = true;
                    int arrLength = Int32.Parse(replyString.Split(' ') [1]);
                    textureArray = new Texture2D[arrLength];
                }
                else
                {
                    switch (replyString)
                    {
                    case "incomingObj":
                        listeningForObj = true;
                        break;

                    case "incomingMtl":
                        listeningForMtl = true;
                        break;

                    case "incomingTexture":
                        listeningForTexture = true;
                        break;

                    case "END_OBJECT":
                        readingInObject = false;
                        Debug.Log("FULL OBJECT RECEIVED");
                        yield return(new WaitForSeconds(0.1f));

                        Array.Reverse(textureArray);
                        if (textureArray.Length > 0 && materialString != null)
                        {
                            GameObject temp = ObjImporter.Import(objectString, materialString, textureArray);
                        }
                        else if (textureArray.Length == 0 || materialString == null)
                        {
                            GameObject temp = ObjImporter.Import(objectString);
                        }
                        //GameObject temp = ObjImporter.Import (objectString, materialString, textureArray);
                        materialString = null;
                        objectString   = null;
                        textureIndex   = 0;
                        break;

                    case "START_OBJECT":
                        readingInObject = true;
                        break;

                    default:
                        if (listeningForObj)
                        {
                            Debug.Log("Mesh incoming...");
                            Debug.Log("Received: " + replyString);
                            objectString    = replyString;
                            listeningForObj = false;
                        }
                        else if (listeningForMtl)
                        {
                            Debug.Log("Material incoming...");
                            Debug.Log("Received: " + replyString);
                            materialString  = replyString;
                            listeningForMtl = false;
                        }
                        else if (listeningForTexture)
                        {
                            Debug.Log("Texture incoming...");
                            Texture2D tempTexture = new Texture2D(1, 1);
                            tempTexture.LoadImage(reply);
                            textureArray[textureIndex] = tempTexture;
                            //textureArray [i] = tempTexture; //OLD ARRAY IMPLEMENTATION
                            //i++;
                            textureIndex++;
                            listeningForTexture = false;
                        }
                        break;
                    }
                }

                /*
                 * if (replyString.Contains ("newmtl")) {
                 *      Debug.Log ("Material incoming...");
                 *      Debug.Log ("Received: "+replyString);
                 *      materialString = replyString;
                 * } else if (replyString.Contains ("object")) {
                 *      Debug.Log ("Mesh incoming...");
                 *      Debug.Log ("Received: "+replyString);
                 *      objectString = replyString;
                 * } else if (replyString == "END_TEXTURES") {
                 *      Debug.Log ("ALL TEXTURES RECEIVED");
                 *      Array.Reverse (textureArray);
                 *      GameObject temp = ObjImporter.Import (objectString, materialString, textureArray);
                 * }
                 * else {
                 *      Debug.Log ("Texture incoming...");
                 *      Texture2D tempTexture = new Texture2D (1, 1);
                 *      tempTexture.LoadImage (reply);
                 *      textureArray [i] = tempTexture;
                 *      i++;
                 * }
                 */

                //GameObject temp = ObjImporter.Import (reply);
                //MeshRenderer renderer = temp.GetComponent<MeshRenderer> ();
                //renderer.materials = DefineMaterial(
                //w.SendString("Hi there"+i++);
                //i++;
            }
            if (w.error != null)
            {
                Debug.LogError("Error: " + w.error);
                break;
            }
            yield return(null);
        }
        w.Close();
    }