Ejemplo n.º 1
0
    public void Start()
    {
        server = new NetworkServerSimple();
        serverOnClientConnect    += ServerOnClientConnect;
        serverOnClientDisconnect += ServerOnClientDisconnect;
        serverOnData             += ServerOnData;

        server.RegisterHandler(MsgType.Connect, serverOnClientConnect);
        server.RegisterHandler(MsgType.Disconnect, serverOnClientDisconnect);
        server.RegisterHandler(TerminalMsgID, serverOnData);

        client              = new NetworkClient();
        clientOnConnect    += ClientOnConnect;
        clientOnDisconnect += ClientOnDisconnect;
        clientOnData       += ClientOnData;

        client.RegisterHandler(MsgType.Connect, clientOnConnect);
        client.RegisterHandler(MsgType.Disconnect, clientOnDisconnect);
        client.RegisterHandler(TerminalMsgID, clientOnData);

        ConnectionConfig myConfig = new ConnectionConfig();

        reliableChannelId   = myConfig.AddChannel(QosType.Reliable);
        unreliableChannelId = myConfig.AddChannel(QosType.Unreliable);

        server.Configure(myConfig, maxConnections);
        client.Configure(myConfig, maxConnections);
    }
Ejemplo n.º 2
0
        void GenerateError(byte error)
        {
            NetworkMessageDelegate msgDelegate = m_MessageHandlers.GetHandler(MsgType.Error);

            if (msgDelegate == null)
            {
                msgDelegate = m_MessageHandlers.GetHandler(MsgType.Error);
            }
            if (msgDelegate != null)
            {
                ErrorMessage msg = new ErrorMessage();
                msg.errorCode = error;

                // write the message to a local buffer
                byte[]        errorBuffer = new byte[200];
                NetworkWriter writer      = new NetworkWriter(errorBuffer);
                msg.Serialize(writer);

                // pass a reader (attached to local buffer) to handler
                NetworkReader reader = new NetworkReader(errorBuffer);

                NetworkMessage netMsg = new NetworkMessage();
                netMsg.msgType   = MsgType.Error;
                netMsg.reader    = reader;
                netMsg.conn      = m_Connection;
                netMsg.channelId = 0;
                msgDelegate(netMsg);
            }
        }
Ejemplo n.º 3
0
        public static AddMessageDelegate SetHandler(int channel, NetworkMessageDelegate handler, Action <ulong> disconnectPeerOnError,
                                                    MyReceiveQueue.Mode mode = MyReceiveQueue.Mode.Synchronized, Func <MyTimeSpan> timestampProvider = null)
        {
            ChannelInfo info;

            if (m_channels.TryGetValue(channel, out info))
            {
                if (info.Queue.ReadMode == mode)
                {
                    info.Handler = handler;
                    return(info.Queue.AddMessage);
                }
                else
                {
                    info.Queue.Dispose();
                }
            }
            info = new ChannelInfo
            {
                Handler = handler,
                Queue   = new MyReceiveQueue(channel, disconnectPeerOnError, mode, mode == MyReceiveQueue.Mode.Synchronized ? 1 : 50, timestampProvider)
            };
            m_channels[channel] = info;

            return(info.Queue.AddMessage);
        }
        public void RegisterHandler(short msgType, NetworkMessageDelegate handler)
        {
            if (handler == null)
            {
                if (NetConfig.logFilter >= LogFilter.Error)
                {
                    Log.Error("RegisterHandler id:" + msgType + " handler is null");
                }
                return;
            }
            if (m_MsgHandlers.ContainsKey(msgType))
            {
                if (NetConfig.logFilter >= LogFilter.Developer)
                {
                    Log.Debug("RegisterHandler replacing " + msgType);
                }

                m_MsgHandlers.Remove(msgType);
            }
            if (NetConfig.logFilter >= LogFilter.Developer)
            {
                Log.Debug("RegisterHandler id:" + msgType + " handler:" + handler.GetMethodName());
            }
            m_MsgHandlers.Add(msgType, handler);
        }
Ejemplo n.º 5
0
 public void connect(string server, NetworkMessageDelegate onConnect)
 {
     client = new NetworkClient ();
     if(onConnect != null)
         client.RegisterHandler (MsgType.Connect, onConnect);
     client.Connect (server, PORT);
 }
 public void RegisterHandler(short msgType, NetworkMessageDelegate handler)
 {
     if (handler == null)
     {
         if (LogFilter.logError)
         {
             Debug.LogError("RegisterHandler id:" + msgType + " handler is null");
         }
     }
     else if (msgType <= 0x1f)
     {
         if (LogFilter.logError)
         {
             Debug.LogError("RegisterHandler: Cannot replace system message handler " + msgType);
         }
     }
     else
     {
         if (this.m_MsgHandlers.ContainsKey(msgType))
         {
             if (LogFilter.logDebug)
             {
                 Debug.Log("RegisterHandler replacing " + msgType);
             }
             this.m_MsgHandlers.Remove(msgType);
         }
         if (LogFilter.logDebug)
         {
             Debug.Log(string.Concat(new object[] { "RegisterHandler id:", msgType, " handler:", DotNetCompatibility.GetMethodName(handler) }));
         }
         this.m_MsgHandlers.Add(msgType, handler);
     }
 }
Ejemplo n.º 7
0
    new public bool InvokeHandler(short msgType, NetworkReader reader, int channelId)
    {
        if (m_MessageHandlersDict.ContainsKey(msgType))
        {
            m_MessageInfo.msgType   = msgType;
            m_MessageInfo.conn      = this;
            m_MessageInfo.reader    = reader;
            m_MessageInfo.channelId = channelId;

            NetworkMessageDelegate msgDelegate = m_MessageHandlersDict[msgType];
            if (msgDelegate == null)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("NetworkConnection InvokeHandler no handler for " + msgType);
                }
                return(false);
            }

            msgDelegate(m_MessageInfo);
            return(true);
        }

        return(false);
    }
Ejemplo n.º 8
0
        public void RegisterHandler(short msgType, NetworkMessageDelegate handler)
        {
            if (handler == null)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("RegisterHandler id:" + msgType + " handler is null");
                }
                return;
            }

            if (msgType <= MsgType.InternalHighest)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("RegisterHandler: Cannot replace system message handler " + msgType);
                }
                return;
            }

            if (m_MsgHandlers.ContainsKey(msgType))
            {
                if (LogFilter.logDebug)
                {
                    Debug.Log("RegisterHandler replacing " + msgType);
                }

                m_MsgHandlers.Remove(msgType);
            }
            if (LogFilter.logDebug)
            {
                Debug.Log("RegisterHandler id:" + msgType + " handler:" + handler.GetMethodName());
            }
            m_MsgHandlers.Add(msgType, handler);
        }
Ejemplo n.º 9
0
        private void ProcessMessages(NetworkMessageDelegate handler, MyTimeSpan delay)
        {
            long delayTicks  = (long)Math.Round(delay.Seconds * Stopwatch.Frequency);
            var  processTime = MyTimeSpan.FromTicks(Stopwatch.GetTimestamp() - delayTicks);

            Message msg;
            int     count = m_receiveQueue.Count;

            while (m_receiveQueue.TryPeek(out msg) && (processTime > msg.ReceivedTime) && count != 0)
            {
                count--;
                if (m_receiveQueue.TryDequeue(out msg)) // Can fail when queue was cleared
                {
                    if (msg.Timestamp != MyTimeSpan.Zero)
                    {
                        msg.Timestamp += delay;
                    }

                    try
                    {
                        handler(msg.Data, msg.Length, msg.UserId, msg.Timestamp, msg.ReceivedTime);
                    }
                    catch (Exception ex)
                    {
                        MyLog.Default.WriteLine(ex);
                        if (!Sandbox.Game.Multiplayer.Sync.IsServer)
                        {
                            throw;
                        }
                        m_disconnectPeerOnError(msg.UserId);
                    }
                    m_messagePool.Return(msg);
                }
            }
        }
 public void RegisterHandler(short msgType, NetworkMessageDelegate handler)
 {
   if (handler == null)
   {
     if (!LogFilter.logError)
       return;
     Debug.LogError((object) ("RegisterHandler id:" + (object) msgType + " handler is null"));
   }
   else if ((int) msgType <= 31)
   {
     if (!LogFilter.logError)
       return;
     Debug.LogError((object) ("RegisterHandler: Cannot replace system message handler " + (object) msgType));
   }
   else
   {
     if (this.m_MsgHandlers.ContainsKey(msgType))
     {
       if (LogFilter.logDebug)
         Debug.Log((object) ("RegisterHandler replacing " + (object) msgType));
       this.m_MsgHandlers.Remove(msgType);
     }
     if (LogFilter.logDebug)
       Debug.Log((object) ("RegisterHandler id:" + (object) msgType + " handler:" + handler.Method.Name));
     this.m_MsgHandlers.Add(msgType, handler);
   }
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Registers a new handler callback for event based system
        /// </summary>
        /// <param name="opcode"></param>
        /// <param name="handler"></param>
        public void RegisterHandler(short opcode, NetworkMessageDelegate handler)
        {
            var op = new Dictionary <short, NetworkMessageDelegate>();

            op.Add(opcode, handler);
            this.handlersMap.Add(op);
        }
Ejemplo n.º 12
0
        protected override void Initialize()
        {
            if ((int)this.UnreliableChannel >= NetworkManager.singleton.channels.Count)
            {
                throw this.Log.CreateUserErrorException("configured 'unreliable' channel is out of range", "set the wrong channel number in the HLAPI Comms Network component", "https://dissonance.readthedocs.io/en/latest/Basics/Quick-Start-UNet-HLAPI/", "B19B4916-8709-490B-8152-A646CCAD788E");
            }
            QosType qosType = NetworkManager.singleton.channels[(int)this.UnreliableChannel];

            if (qosType != QosType.Unreliable)
            {
                throw this.Log.CreateUserErrorException(string.Format("configured 'unreliable' channel has QoS type '{0}'", qosType), "not creating the channel with the correct QoS type", "https://dissonance.readthedocs.io/en/latest/Basics/Quick-Start-UNet-HLAPI/", "24ee53b1-7517-4672-8a4a-64a3e3c87ef6");
            }
            if ((int)this.ReliableSequencedChannel >= NetworkManager.singleton.channels.Count)
            {
                throw this.Log.CreateUserErrorException("configured 'reliable' channel is out of range", "set the wrong channel number in the HLAPI Comms Network component", "https://dissonance.readthedocs.io/en/latest/Basics/Quick-Start-UNet-HLAPI/", "5F5F2875-ECC8-433D-B0CB-97C151B8094D");
            }
            QosType qosType2 = NetworkManager.singleton.channels[(int)this.ReliableSequencedChannel];

            if (qosType2 != QosType.ReliableSequenced)
            {
                throw this.Log.CreateUserErrorException(string.Format("configured 'reliable sequenced' channel has QoS type '{0}'", qosType2), "not creating the channel with the correct QoS type", "https://dissonance.readthedocs.io/en/latest/Basics/Quick-Start-UNet-HLAPI/", "035773ec-aef3-477a-8eeb-c234d416171c");
            }
            short typeCode = this.TypeCode;

            if (HlapiCommsNetwork.< > f__mg$cache0 == null)
            {
                HlapiCommsNetwork.< > f__mg$cache0 = new NetworkMessageDelegate(HlapiCommsNetwork.NullMessageReceivedHandler);
            }
            NetworkServer.RegisterHandler(typeCode, HlapiCommsNetwork.< > f__mg$cache0);
            base.Initialize();
        }
Ejemplo n.º 13
0
    private void GenerateError(int error)
    {
        NetworkError netError = (NetworkError)error;

        if (LogFilter.logError)
        {
            Debug.LogError("Client Net Error: " + netError);
        }

        NetworkMessageDelegate msgDelegate = handlers.ContainsKey(MsgType.Error) ? handlers[MsgType.Error] : null;

        if (msgDelegate != null)
        {
            ErrorMessage msg = new ErrorMessage();
            msg.errorCode = error;

            // write the message to a local buffer
            byte[]        errorBuffer = new byte[200];
            NetworkWriter writer      = new NetworkWriter(errorBuffer);
            msg.Serialize(writer);

            // pass a reader (attached to local buffer) to handler
            NetworkReader reader = new NetworkReader(errorBuffer);

            NetworkMessage netMsg = new NetworkMessage();
            netMsg.msgType   = MsgType.Error;
            netMsg.reader    = reader;
            netMsg.conn      = m_myConnection;
            netMsg.channelId = 0;
            msgDelegate(netMsg);
        }
    }
Ejemplo n.º 14
0
 public void startServer(NetworkMessageDelegate onConnect)
 {
     NetworkServer.Listen (PORT);
     if (onConnect != null) {
         NetworkServer.RegisterHandler (MsgType.Connect, onConnect);
     }
 }
Ejemplo n.º 15
0
 public GameMessage(NetworkMessageDelegate method)
 {
     index       = MessageManager.LastIndex;
     this.method = method;
     MessageManager.LastIndex++;
     MessageManager.ToRegister.Add(this);
 }
Ejemplo n.º 16
0
        // ===========================================================================
        // ========================= UTILITY FUNCTIONS =========================
        // ===========================================================================

        void registerAllCallbacks(NetworkClient nc, NetworkMessageDelegate nmd)
        {
            foreach (Message.ID MsgId in System.Enum.GetValues(typeof(Message.ID)))             // Register all the callbacks
            {
                nc.RegisterHandler((short)MsgId, nmd);
            }
        }
        internal void RegisterHandlerSafe(short msgType, NetworkMessageDelegate handler)
        {
            if (handler == null)
            {
                if (NetConfig.logFilter >= LogFilter.Error)
                {
                    Log.Error("RegisterHandlerSafe id:" + msgType + " handler is null");
                }
                return;
            }

            if (NetConfig.logFilter >= LogFilter.Developer)
            {
                Log.Debug("RegisterHandlerSafe id:" + msgType + " handler:" + handler.GetMethodName());
            }
            if (m_MsgHandlers.ContainsKey(msgType))
            {
                if (NetConfig.logFilter >= LogFilter.Error)
                {
                    Log.Error("RegisterHandlerSafe id:" + msgType + " handler:" + handler.GetMethodName() + " conflict");
                }
                return;
            }
            m_MsgHandlers.Add(msgType, handler);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Send message to server to update a player
        /// Cannot change the actual playerKey.  if that is desired, remove player / add new player
        /// </summary>
        /// <param name="playerKey"></param>
        /// <param name="playerValue"></param>
        /// <param name="flags"></param>
        /// <param name="response"></param>
        public void UpdatePlayer(string playerKey, string playerValue, int flags, NetworkMessageDelegate response = null)
        {
            if (IsConnected)
            {
                if (IsDebug)
                {
                    Debug.Log("<ClientHost> Updating Player [" + playerKey + "]");
                }
                var msg = new MessageTypes.UpdatePlayerMessage();
                msg.playerKey   = playerKey;
                msg.playerValue = playerValue;
                msg.flags       = flags;
                Client.Send(MessageTypes.UpdatePlayer, msg);

                // use response type for handler!
                if (response != null)
                {
                    RegisterHandler(MessageTypes.UpdatePlayerResponse, response);
                }
            }
            else
            {
                Debug.LogError("<ClientHost> UpdatePlayer failed, host not connected to MasterServer");
            }
        }
Ejemplo n.º 19
0
 public static void RegisterHandler(int msgType, NetworkMessageDelegate handler)
 {
     if (handlers.ContainsKey(msgType))
     {
         if (LogFilter.Debug) Debug.Log("NetworkServer.RegisterHandler replacing " + msgType);
     }
     handlers[msgType] = handler;
 }
 /// <summary>
 /// Sets a message handler.
 /// </summary>
 /// <param name="msgType">Message type.</param>
 /// <param name="handler">Handler.</param>
 public virtual void SetMessageHandler(short msgType, NetworkMessageDelegate handler)
 {
     #if SERVER
     NetworkServer.
     #else
     client.
     #endif
     RegisterHandler(msgType, handler);
 }
Ejemplo n.º 21
0
        public void Init()
        {
            m_Delegates = new Dictionary <DelegateType, Delegate>();
            NetworkMessageDelegate  networkMessageDelegate  = null;
            ConnectionErrorDelegate connectionErrorDelegate = null;

            m_Delegates.Add(DelegateType.ConnectionError, connectionErrorDelegate);
            m_Delegates.Add(DelegateType.NetworkMessage, networkMessageDelegate);
        }
Ejemplo n.º 22
0
        public override void RegisterMessaging(short msgType, [NotNull] NetworkMessageDelegate callback)
        {
            if (_client.handlers.ContainsKey(msgType))
            {
                Debug.LogError($"MsgId: {msgType}, already exists, overriding . . .");
            }

            _client.RegisterHandler(msgType, callback);
        }
Ejemplo n.º 23
0
 private void RegisterEvent(NetworkClient p_client, short msg_id, NetworkMessageDelegate p_callback)
 {
     if (_client == null)
     {
         return;
     }
     _client.UnregisterHandler(msg_id);
     _client.RegisterHandler(msg_id, p_callback);
 }
Ejemplo n.º 24
0
    public void RegisterHandler(short msgType, NetworkMessageDelegate handler)
    {
        if (msgHandlers.ContainsKey(msgType))
        {
            msgHandlers.Remove(msgType);
        }

        msgHandlers.Add(msgType, handler);
    }
Ejemplo n.º 25
0
        public void RegisterHandlerOverride(short _msgType, NetworkMessageDelegate handler)
        {
            if (NetworkServer.handlers.ContainsKey(_msgType))
            {
                NetworkServer.handlers.Remove(_msgType);
            }

            NetworkServer.RegisterHandler(_msgType, handler);
        }
Ejemplo n.º 26
0
        public void RegisterHandlerOverride(short _msgType, NetworkMessageDelegate handler)
        {
            if (networkClient.handlers.ContainsKey(_msgType))
            {
                networkClient.handlers.Remove(_msgType);
            }

            networkClient.RegisterHandler(_msgType, handler);
        }
Ejemplo n.º 27
0
 public bool InvokeHandler(NetworkMessage netMsg)
 {
     if (m_MessageHandlersDict.ContainsKey(netMsg.msgType))
     {
         NetworkMessageDelegate msgDelegate = m_MessageHandlersDict[netMsg.msgType];
         msgDelegate(netMsg);
         return(true);
     }
     return(false);
 }
Ejemplo n.º 28
0
    public static void RegisterNetworkHandlerAttributes()
    {
        List <NetworkMessageHandlerAttribute> serverMessageHandlers = (List <NetworkMessageHandlerAttribute>)get_serverMessageHandlers.GetValue(null);
        List <NetworkMessageHandlerAttribute> clientMessageHandlers = (List <NetworkMessageHandlerAttribute>)get_clientMessageHandlers.GetValue(null);


        HashSet <short> hashSet = new HashSet <short>();

        Type[] types = typeof(NetworkHandler).Assembly.GetTypes();
        for (int i = 0; i < types.Length; i++)
        {
            foreach (MethodInfo methodInfo in types[i].GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
            {
                object[] customAttributes = methodInfo.GetCustomAttributes(false);
                foreach (var attribute in customAttributes.OfType <NetworkMessageHandlerAttribute>())
                {
                    NetworkMessageHandlerAttribute networkMessageHandlerAttribute = (Attribute)attribute as NetworkMessageHandlerAttribute;

                    NetworkMessageDelegate messageHandler = null;
                    if (networkMessageHandlerAttribute != null)
                    {
                        messageHandler = (NetworkMessageDelegate)Delegate.CreateDelegate(typeof(NetworkMessageDelegate), methodInfo);
                        if (messageHandler != null)
                        {
                            if (networkMessageHandlerAttribute.client)
                            {
                                clientMessageHandlers.Add(networkMessageHandlerAttribute);
                                hashSet.Add(networkMessageHandlerAttribute.msgType);
                            }
                            if (networkMessageHandlerAttribute.server)
                            {
                                serverMessageHandlers.Add(networkMessageHandlerAttribute);
                                hashSet.Add(networkMessageHandlerAttribute.msgType);
                            }
                        }
                        if (messageHandler == null)
                        {
                            Debug.LogWarningFormat("Could not register message handler for {0}. The function signature is likely incorrect.", new object[]
                            {
                                methodInfo.Name
                            });
                        }
                        get_messageHandler.SetValue(networkMessageHandlerAttribute, messageHandler);
                        if (!networkMessageHandlerAttribute.client && !networkMessageHandlerAttribute.server)
                        {
                            Debug.LogWarningFormat("Could not register message handler for {0}. It is marked as neither server nor client.", new object[]
                            {
                                methodInfo.Name
                            });
                        }
                    }
                }
            }
        }
    }
Ejemplo n.º 29
0
    private void StartNetServer()
    {
        serverOnClientConnect    += ServerOnClientConnect;
        serverOnClientDisconnect += ServerOnClientDisconnect;

        msgServer.RegisterHandler(MsgType.Connect, serverOnClientConnect);
        msgServer.RegisterHandler(MsgType.Disconnect, serverOnClientDisconnect);

        msgServer.Listen(serverListenPort);
        Debug.Log("Starting message server on port " + serverListenPort);
    }
Ejemplo n.º 30
0
 public void RegisterHandler(short msgType, NetworkMessageDelegate handler)
 {
     if (m_MessageHandlers.ContainsKey(msgType))
     {
         if (LogFilter.Debug)
         {
             Debug.Log("NetworkConnection.RegisterHandler replacing " + msgType);
         }
     }
     m_MessageHandlers[msgType] = handler;
 }
Ejemplo n.º 31
0
 public static void RegisterHandler(int msgType, NetworkMessageDelegate handler)
 {
     if (handlers.ContainsKey(msgType))
     {
         if (LogFilter.Debug)
         {
             Debug.Log("NetworkClient.RegisterHandler replacing " + handler.ToString() + " - " + msgType);
         }
     }
     handlers[msgType] = handler;
 }
Ejemplo n.º 32
0
    new protected void HandleReader(
        NetworkReader reader,
        int receivedSize,
        int channelId)
    {
        // read until size is reached.
        // NOTE: stream.Capacity is 1300, NOT the size of the available data
        while (reader.Position < receivedSize)
        {
            // the reader passed to user code has a copy of bytes from the real stream. user code never touches the real stream.
            // this ensures it can never get out of sync if user code reads less or more than the real amount.
            ushort sz      = reader.ReadUInt16();
            short  msgType = reader.ReadInt16();

            // create a reader just for this message
            byte[]        msgBuffer = reader.ReadBytes(sz);
            NetworkReader msgReader = new NetworkReader(msgBuffer);

            if (logNetworkMessages)
            {
                StringBuilder msg = new StringBuilder();
                for (int i = 0; i < sz; i++)
                {
                    msg.AppendFormat("{0:X2}", msgBuffer[i]);
//					if (i > k_MaxMessageLogSize) break;
                }
                Debug.Log("ConnectionRecv con:" + connectionId + " bytes:" + sz + " msgId:" + msgType + " " + msg);
            }

            NetworkMessageDelegate msgDelegate = null;
            if (m_MessageHandlersDict.ContainsKey(msgType))
            {
                msgDelegate = m_MessageHandlersDict[msgType];
            }
            if (msgDelegate != null)
            {
                m_NetMsg.msgType   = msgType;
                m_NetMsg.reader    = msgReader;
                m_NetMsg.conn      = this;
                m_NetMsg.channelId = channelId;
                msgDelegate(m_NetMsg);
                lastMessageTime = Time.time;
            }
            else
            {
                //NOTE: this throws away the rest of the buffer. Need moar error codes
                if (LogFilter.logError)
                {
                    Debug.LogError("Unknown message ID " + msgType + " connId:" + connectionId);
                }
                break;
            }
        }
    }
Ejemplo n.º 33
0
 public void RegisterHandler(short msgType, NetworkMessageDelegate handler)
 {
     if (!_msgHandler.ContainsKey(msgType))
     {
         _msgHandler.Add(msgType, handler);
     }
     else
     {
         _msgHandler[msgType] = handler;
     }
 }
Ejemplo n.º 34
0
        public void RegisterHandler(short messageType, NetworkMessageDelegate handler)
        {
#if DEBUG
            if (__client == null)
            {
                throw new InvalidOperationException();
            }
#endif

            __client.RegisterHandler(messageType, handler);
        }
 internal void RegisterHandlerSafe(short msgType, NetworkMessageDelegate handler)
 {
   if (handler == null)
   {
     if (!LogFilter.logError)
       return;
     Debug.LogError((object) ("RegisterHandlerSafe id:" + (object) msgType + " handler is null"));
   }
   else
   {
     if (LogFilter.logDebug)
       Debug.Log((object) ("RegisterHandlerSafe id:" + (object) msgType + " handler:" + handler.Method.Name));
     if (this.m_MsgHandlers.ContainsKey(msgType))
       return;
     this.m_MsgHandlers.Add(msgType, handler);
   }
 }
 internal void RegisterHandlerSafe(short msgType, NetworkMessageDelegate handler)
 {
     if (handler == null)
     {
         if (LogFilter.logError)
         {
             Debug.LogError("RegisterHandlerSafe id:" + msgType + " handler is null");
         }
     }
     else
     {
         if (LogFilter.logDebug)
         {
             Debug.Log(string.Concat(new object[] { "RegisterHandlerSafe id:", msgType, " handler:", DotNetCompatibility.GetMethodName(handler) }));
         }
         if (!this.m_MsgHandlers.ContainsKey(msgType))
         {
             this.m_MsgHandlers.Add(msgType, handler);
         }
     }
 }
        public static AddMessageDelegate SetHandler(int channel, NetworkMessageDelegate handler, MyReceiveQueue.Mode mode = MyReceiveQueue.Mode.Synchronized, Func<TimeSpan> timestampProvider = null)
        {
            ChannelInfo info;
            if (m_channels.TryGetValue(channel, out info))
            {
                if (info.Queue.ReadMode == mode)
                {
                    info.Handler = handler;
                    return info.Queue.AddMessage;
                }
                else
                {
                    info.Queue.Dispose();
                }
            }
            info = new ChannelInfo();
            info.Handler = handler;
            info.Queue = new MyReceiveQueue(channel, mode, mode == MyReceiveQueue.Mode.Synchronized ? 1 : 50, timestampProvider);
            m_channels[channel] = info;

            return info.Queue.AddMessage;
        }
 public void RegisterHandler(short msgType, NetworkMessageDelegate handler)
 {
     if (handler == null)
     {
         if (LogFilter.logError)
         {
             Debug.LogError("RegisterHandler id:" + msgType + " handler is null");
         }
         return;
     }
     if (msgType <= 31)
     {
         if (LogFilter.logError)
         {
             Debug.LogError("RegisterHandler: Cannot replace system message handler " + msgType);
         }
         return;
     }
     if (this.m_MsgHandlers.ContainsKey(msgType))
     {
         if (LogFilter.logDebug)
         {
             Debug.Log("RegisterHandler replacing " + msgType);
         }
         this.m_MsgHandlers.Remove(msgType);
     }
     if (LogFilter.logDebug)
     {
         Debug.Log(string.Concat(new object[]
         {
             "RegisterHandler id:",
             msgType,
             " handler:",
             handler.Method.Name
         }));
     }
     this.m_MsgHandlers.Add(msgType, handler);
 }
Ejemplo n.º 39
0
		// ===========================================================================
		// ========================= UTILITY FUNCTIONS =========================
		// ===========================================================================

		void registerAllCallbacks ( NetworkClient nc, NetworkMessageDelegate nmd )
		{
			foreach (Message.ID MsgId in System.Enum.GetValues(typeof(Message.ID))) // Register all the callbacks
				nc.RegisterHandler((short)MsgId, nmd);
		}
Ejemplo n.º 40
0
 public void connectToLocal(NetworkMessageDelegate onConnect)
 {
     client = ClientScene.ConnectLocalServer ();
     client.RegisterHandler (MsgType.Connect, onConnect);
 }
 internal void RegisterHandlerSafe(short msgType, NetworkMessageDelegate handler)
 {
     if (handler == null)
     {
         if (LogFilter.logError)
         {
             Debug.LogError("RegisterHandlerSafe id:" + msgType + " handler is null");
         }
         return;
     }
     if (LogFilter.logDebug)
     {
         Debug.Log(string.Concat(new object[]
         {
             "RegisterHandlerSafe id:",
             msgType,
             " handler:",
             handler.Method.Name
         }));
     }
     if (this.m_MsgHandlers.ContainsKey(msgType))
     {
         return;
     }
     this.m_MsgHandlers.Add(msgType, handler);
 }
Ejemplo n.º 42
0
        /// <summary>
        /// Processes messages
        /// Delay indicates how long must be message in queue before processing (lag emulation)
        /// </summary>
        public void Process(NetworkMessageDelegate handler, TimeSpan delay = default(TimeSpan))
        {
            if (ReadMode == Mode.Synchronized)
            {
                // Process old messages (stored because of delay)
                if (m_receiveQueue.Count > 0)
                {
                    ProcessMessages(handler, delay);
                }

                // Read and process all of them cuz it might ping-pong msgs between server-client all the time
                while (ReceiveOne());

                ProcessMessages(handler, delay);
            }
            else
            {
                ProcessMessages(handler, delay);
            }
        }
Ejemplo n.º 43
0
        private void ProcessMessages(NetworkMessageDelegate handler, TimeSpan delay)
        {
            long delayTicks = (long)Math.Round(delay.TotalSeconds * Stopwatch.Frequency);
            long processTime = Stopwatch.GetTimestamp() - delayTicks;

            Message msg;
            int count = m_receiveQueue.Count;
            while (m_receiveQueue.TryPeek(out msg) && (processTime > msg.ReceiveTime) && count != 0)
            {
                count--;
                if (m_receiveQueue.TryDequeue(out msg)) // Can fail when queue was cleared
                {
                    if (msg.Timestamp != TimeSpan.Zero)
                    {
                        msg.Timestamp += delay;
                    }

                    handler(msg.Data, msg.Length, msg.UserId, msg.Timestamp);
                    m_messagePool.Return(msg);
                }
            }
        }
Ejemplo n.º 44
0
 /// <summary>
 /// 
 /// <para>
 /// Register a handler for a particular message type.
 /// </para>
 /// 
 /// </summary>
 /// <param name="msgType">Message type number.</param><param name="handler">Function handler which will be invoked for when this message type is received.</param>
 public static void RegisterHandler(short msgType, NetworkMessageDelegate handler)
 {
     NetworkServer.instance.m_MessageHandlers.RegisterHandler(msgType, handler);
 }
Ejemplo n.º 45
0
        /// <summary>
        /// Processes messages
        /// Delay indicates how long must be message in queue before processing (lag emulation)
        /// </summary>
        public void Process(NetworkMessageDelegate handler, TimeSpan delay = default(TimeSpan))
        {
            if (ReadMode == Mode.Synchronized)
            {
                // Process old messages (stored because of delay)
                if (m_receiveQueue.Count > 0)
                {
                    ProcessMessages(handler, delay);
                }

                // Read and process one-by-one to keep memory usage low
                while (ReceiveOne())
                {
                    ProcessMessages(handler, delay);
                }
            }
            else
            {
                ProcessMessages(handler, delay);
            }
        }
Ejemplo n.º 46
0
 /// <summary>
 /// <para>Register a handler for a particular message type.</para>
 /// </summary>
 /// <param name="msgType">Message type number.</param>
 /// <param name="handler">Function handler which will be invoked for when this message type is received.</param>
 public static void RegisterHandler(short msgType, NetworkMessageDelegate handler)
 {
     instance.m_SimpleServerSimple.RegisterHandler(msgType, handler);
 }
Ejemplo n.º 47
0
 /// <summary>
 /// <para>This registers a handler function for a message Id.</para>
 /// </summary>
 /// <param name="msgType">The message ID to register.</param>
 /// <param name="handler">The handler function to register.</param>
 public void RegisterHandler(short msgType, NetworkMessageDelegate handler)
 {
     this.m_MessageHandlers.RegisterHandler(msgType, handler);
 }