예제 #1
0
        public void OnDataReceived(ConnectionId connectionId, IPEndPoint endpoint, NetBuffer reader)
        {
            _messageMetaData.SequenceNumber = reader.ReadSequenceNumber();
            _messageMetaData.ConnectionId   = connectionId;
            _messageMetaData.EndPoint       = endpoint;
            _messageMetaData.Latency        = _latencyInfo.GetLatency(connectionId);

            //Debug.Log("receiving data from " + endpoint);
            while (reader.PositionInBytes < reader.LengthBytes)
            {
                var messageSize          = reader.ReadVariableUInt32();
                var messageStartPosition = reader.PositionInBytes;
                var messageType          = reader.ReadMessageType();

                _messageMetaData.MessageType = messageType;

                Action <MessageMetaData, NetBuffer> handler;
                if (_handlers.TryGetValue(messageType, out handler))
                {
                    handler(_messageMetaData, reader);
                }
                // Skip bytes that weren't read
                var bytesRead   = reader.PositionInBytes - messageStartPosition;
                var bytesToSkip = messageSize - bytesRead;
                if (bytesRead > messageSize)
                {
                    // TODO How to handle this error?
                    throw new Exception("Error! Bytes read (" + bytesRead + ") > messageSizeInBytes (" + messageSize + ")" + ", reader posInBytes: " + reader.PositionInBytes);
                }
                reader.SkipBytes(bytesToSkip);
            }
        }
        public void Dispatch(MessageType messageType, IObjectMessage message, ConnectionId connectionId, ObjectRole sender)
        {
            IList <ObjectMessageHandler> handlers;

            if (_registeredHandlers.TryGetValue(messageType, out handlers))
            {
                for (int i = 0; i < handlers.Count; i++)
                {
                    var handler = handlers[i];
                    if ((handler.MetaData.AllowedSenders & sender) != 0)
                    {
                        handler.Invoke(message, new MessageMetadata(connectionId, _latencyInfo.GetLatency(connectionId)));
                    }
                    else
                    {
                        Debug.Log(sender + " is not allowed to send message of type " + message.GetType());
                    }
                }
            }
        }