Example #1
0
    protected void startReceiving()
    {
        elasticServerTimeout = serverTimeout;
        done = false;
        timer.Start();
        lastMessageTS = timer.getElapsedMS();

        UnityEngine.Debug.Log("Client: start processing incoming messages");
        while (!done)
        {
            NetMQMessage msg = new NetMQMessage();
            //If client receives any message, it means that the client is connected
            if (subscriber.TryReceiveMultipartMessage(TimeSpan.FromMilliseconds(1), ref msg, 2))
            {
                isConnected          = true;
                lastMessageTS        = timer.getElapsedMS();
                elasticServerTimeout = serverTimeout;

                System.Diagnostics.Debug.Assert(msg.First.Buffer[0] == (byte)'A');
                UInt64 signature = messageSignature(msg.First.Buffer[1], msg.First.Buffer[2]);

                Action <NetMQMessage> f = null;
                try
                {
                    f = messageHandlers[signature];
                }
                catch (KeyNotFoundException)
                {
                    //UnityEngine.Debug.Log(
                    //    String.Format("Client: key {0} was not present in messageHandlers, module {1}, action {2}",
                    //    signature, msg.First.Buffer[1], msg.First.Buffer[2]));
                }
                if (f != null)
                {
                    f(msg);
                }
            }
            else
            {
                float elapsed = (timer.getElapsedMS() - lastMessageTS) * 0.001f;
                if (elapsed > elasticServerTimeout)
                {
                    isConnected = false;

                    UnityEngine.Debug.Log(String.Format("Connection to the server lost for {0} seconds", elapsed));
                    elasticServerTimeout *= 2;
                }

                Thread.Sleep(TimeSpan.FromMilliseconds(1));
            }
        }

        UnityEngine.Debug.Log("Client: main-loop ends");
    }