示例#1
0
        private async Task CommandAsync(PacketPayload payload, CancellationToken cancellationToken)
        {
            await _completionLock.WaitAsync(cancellationToken).ConfigureAwait(false);

            _commandCompletionSource = new TaskCompletionSource <Packet>();

            try
            {
                var packet = new Packet
                {
                    Content = new PacketContent
                    {
                        Payload = payload
                    }
                };

                Send(packet);

                var responsePacket = await _commandCompletionSource.Task.ConfigureAwait(false);

                var messageId = responsePacket.Content.MessageId;

                if (messageId != MessageId.ACK_ACK)
                {
                    throw new InvalidOperationException($"Received {messageId}");
                }
            }
            finally
            {
                _completionLock.Release();
            }
        }
示例#2
0
        public bool TryProcessPayload(PacketPayload payload, IMessageParameters parameters, INetPeer peer)
        {
            Logger.DebugFormat("Recieved Payload Type: {0} from Peer: {1}", payload?.GetType(), peer.PeerDetails.ConnectionID);

            //Always return false for logging so we don't consume
            return(false);
        }
示例#3
0
		/// <summary>
		/// Handles outgoing requests using the internal registered middlewares.
		/// </summary>
		/// <param name="request">Request to process.</param>
		/// <param name="payload">Payload to process.</param>
		private void ProcessRequestMiddlewares(IRestRequest request, PacketPayload payload)
		{
			//We move forward through the middlewares to give them a chance
			//to process the requests.
			for (int i = 0; i < restsharpMiddlewares.Count; i++)
				restsharpMiddlewares[i].ProcessOutgoingRequest(request, payload);
		}
        public virtual async Task <IActionResult> Post([FromBody] RequestMessage gladNetRequest)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestResult());
            }

            //This is an ASP server. We can ONLY send back to the original sender so we can enable routeback
            //This works because if there is anything in the routing stack it wasn't from this ASP server so we can enable
            //routeback and it'll be sent back through the system

            TPayloadType payload = gladNetRequest?.Payload?.Data as TPayloadType;

            if (payload == null)
            {
                return(new BadRequestResult());
            }

            PacketPayload responsePayload = await HandlePost(payload);

            ResponseMessage responseMessage = new ResponseMessage(responsePayload);

            //Now check routeback info
            if (gladNetRequest.isMessageRoutable)
            {
                gladNetRequest.ExportRoutingDataTo(responseMessage);
                responseMessage.isRoutingBack = true;
            }

            //Return an ASP result
            return(new GladNetObjectResult(responseMessage));
        }
        public bool ProcessOutgoingRequest(IRestRequest request, PacketPayload payload)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            //If the payload requires authorization to handle on the server then we should
            //send the JWT header with the request.

            //Check if the payload requires authorizatation
            if (!payload.GetType().HasAttribute <AuthorizationRequiredAttribute>())
            {
                return(true);                //return true means the middleware didn't encounter a failure
            }
            //If an authorization required payload is being sent but we have no token we must
            //throw an error
            if (!tokenService.isTokenAvailable)
            {
                throw new InvalidOperationException($"{nameof(ITokenService)} indicated the token was unavailable. Service cannot send {payload.GetType().Name} as it requires the token to authenticate.");
            }

            request.AddHeader("Authorization", tokenService.FullTokenHeaderValue);

            return(true);
        }
示例#6
0
        /// <summary>
        /// Process the outgoing <see cref="IRestRequest"/> and returning false to indicate a failure.
        /// </summary>
        /// <param name="request">The rest request.</param>
        /// <param name="payload">The <see cref="PacketPayload"/> being sent.</param>
        /// <returns>True if the middleware processed the request and false if there was an error.</returns>
        public bool ProcessOutgoingRequest(IRestRequest request, PacketPayload payload)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            AuthenticationRequest requestPayload = payload as AuthenticationRequest;

            //We return true to indicate the middleware functioned correctly
            if (requestPayload == null)
            {
                return(true);
            }

            //Clear out the normal parameters
            request.Parameters.Clear();

            //the JWT service is expecting authentication to be query string in the body
            //In this form: username=Admin&password=Test123$&grant_type=password
            request.AddParameter("application/x-www-form-urlencoded", $"username={requestPayload.UserName}&password={requestPayload.Password}&grant_type=password", ParameterType.RequestBody);

            return(true);
        }
示例#7
0
		/// <summary>
		/// Enqueues a webrequest to be handled with the provided serialized data.
		/// This 
		/// </summary>
		/// <param name="requestPayload">Request payload.</param>
		/// <param name="requestName">String <see cref="Type"/> name of the <see cref="PacketPayload"/> type.</param>
		/// <returns>Returns the result of the enqueued request.</returns>
		public SendResult EnqueueRequest(PacketPayload requestPayload)
		{
			//Check param
			if (requestPayload == null)
				throw new ArgumentNullException(nameof(requestPayload), $"Provided parameter request payload {requestPayload} is null.");

			return EnqueueRequest(new RequestMessage(requestPayload), requestPayload.GetType().Name, requestPayload);
		}
        public SendResult SendEvent(PacketPayload payload, DeliveryMethod deliveryMethod, bool encrypt = false, byte channel = 0)
        {
            //TODO: Get true broadcasting functionality
            foreach (INetPeer p in peers)
            {
                p.TrySendMessage(OperationType.Event, payload, deliveryMethod, encrypt, channel);
            }

            //This is a 1 to N broadcast. Can't really respond with full details using a SendResult
            return(SendResult.Sent);
        }
示例#9
0
 /// <summary>
 /// Attempts to send a message using the provided <see cref="PacketPayload"/>.
 /// </summary>
 /// <param name="opType">The outgoing <see cref="OperationType"/>.</param>
 /// <param name="payload">The <see cref="PacketPayload"/> to send with the message.</param>
 /// <param name="deliveryMethod">Delivery method to use for the message.</param>
 /// <param name="encrypt">Indicates if the message should be encrypted.</param>
 /// <param name="channel">Channel to send on.</param>
 /// <returns>Indicates the status of the outgoing message attempt.</returns>
 public SendResult TrySendMessage(OperationType opType, PacketPayload payload, DeliveryMethod deliveryMethod, bool encrypt = false, byte channel = 0)
 {
     if (opType == OperationType.Request)
     {
         return(messageSendingService.SendRequest(payload, deliveryMethod, encrypt, channel));
     }
     else
     {
         throw new ArgumentException($"Cannot send OperationType: {opType} from client peers.", nameof(opType));
     }
 }
示例#10
0
        private void Poll(PacketPayload packetPayload)
        {
            var packet = new Packet
            {
                Content = new PacketContent
                {
                    Payload = packetPayload
                }
            };

            Send(packet);
        }
 protected override void OnReceiveRequest(PacketPayload payload, IMessageParameters parameters)
 {
     //We're not interested in unencrypted messages on the ProxyLoadBalancing server
     if (!parameters.Encrypted)
     {
         return;
     }
     else
     {
         Logger.WarnFormat("Client: {0} at IP {1} tried to send unencrypted payload Type: {2}", PeerDetails.ConnectionID, PeerDetails.RemoteIP.ToString(), payload.GetType());
     }
 }
示例#12
0
		public SendResult EnqueueRequest(byte[] serializedRequest, string payloadName, PacketPayload payload)
		{
			if (serializedRequest == null) throw new ArgumentNullException(nameof(serializedRequest));
			if (payload == null) throw new ArgumentNullException(nameof(payload));
			if (string.IsNullOrEmpty(payloadName)) throw new ArgumentException($"Failed to determine endpoint URL due to invalid or unavailable payload name.", nameof(payloadName));

			//TODO: Cache non-generic name
			//Create a new request that targets the API/RequestName controller
			//on the ASP server.
			RestRequest request = new RestRequest($"/api/{GetNameWithoutGenericArity(payloadName)}", Method.POST);

			//TODO: Don't just assume serialization format
			//sends the request with the protobuf content type header.
			request.AddParameter("application/gladnet", serializedRequest, ParameterType.RequestBody);

			//Below we process outgoing and then incoming middlewares
			ProcessRequestMiddlewares(request, payload);

			IRestResponse response = httpClient.Post(request);

			ProcessResponseMiddlewares(response);

			//We should check the bytes returned in a response
			//We expect a NetworkMessage (in GladNet2 to preserve routing information)
			if (response.RawBytes != null && response.RawBytes.Count() > 0)
			{
				//With GladNet we expect to get back a NetworkMessage so we should attempt to deserialize one.
				ResponseMessage responseMessage = deserializer.Deserialize<ResponseMessage>(response.RawBytes);

#if !ENDUSER
				//If the message is routing back we don't need it to hit the user.
				//We can routeback now
				if(responseMessage.isRoutingBack)
				{
					//This is a difficult decision but we should indicate Sent after routing back as the message definitely was sent
					messageRoutebackService.Route(responseMessage, DefaultWebMessageParameters.Default); //TODO: Deal with message parameters

					return SendResult.Sent; //return, don't let the message be dispatched
				}

				//For GladNet2 2.x routing we have to push the AUID into the response message if it's not routing back
				responseMessage.Push(pairedConnectionAUID);
#endif

				//Must deserialize the payload before it reaches the user.
				responseMessage.Payload.Deserialize(deserializer);

				responseMessage.Dispatch(responseMessageRecieverService, DefaultWebMessageParameters.Default); //TODO: Add message parameters.
			}

			return SendResult.Sent;
		}
        public SendResult SendRequest(PacketPayload payload, DeliveryMethod deliveryMethod, bool encrypt = false, byte channel = 0)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload), $"Payload parameter {payload} must not be null.");
            }

            //Right now we just ignore the payload args
            //TODO: Implement support for args

            //Requests are sent to ASP controlls based on the payload type names.
            return(requestEnqueueStrat.EnqueueRequest(payload));
        }
示例#14
0
        /// <summary>
        /// Sends a Photon response message with the provided parameters
        /// </summary>
        /// <param name="payload">Payload to send with the message.</param>
        /// <param name="unreliable">Indicates if the message should be sent unreliabily.</param>
        /// <param name="encrypt">Indicates if the message should be encrypted.</param>
        /// <param name="channel">Channel to send the message on.</param>
        /// <returns>Indicates the result of sending the message.</returns>
        private Photon.SocketServer.SendResult SendResponse(PacketPayload payload, bool unreliable, bool encrypt, byte channel)
        {
            //Builds the message in a context that Photon understands (dictionary of objects)
            OperationResponse data = new OperationResponse(1, new Dictionary <byte, object>(1)
            {
                { 0, SerializePayload(payload) }
            });

            //Sends the event through Photon's transport layer.
            return(photonPeer.SendOperationResponse(data, new SendParameters()
            {
                ChannelId = channel, Encrypted = encrypt, Unreliable = unreliable
            }));
        }
示例#15
0
        /// <summary>
        /// Attempts to send a message using the provided <see cref="PacketPayload"/>.
        /// </summary>
        /// <param name="opType">The outgoing <see cref="OperationType"/>.</param>
        /// <param name="payload">The <see cref="PacketPayload"/> to send with the message.</param>
        /// <param name="deliveryMethod">Delivery method to use for the message.</param>
        /// <param name="encrypt">Indicates if the message should be encrypted.</param>
        /// <param name="channel">Channel to send on.</param>
        /// <returns>Indicates the status of the outgoing message attempt.</returns>
        public GladNet.Common.SendResult TrySendMessage(OperationType opType, PacketPayload payload, DeliveryMethod deliveryMethod, bool encrypt = false, byte channel = 0)
        {
            Photon.SocketServer.SendResult result;

            //Depending on the operation type we'll need to call different methods on the peer to send
            switch (opType)
            {
            case OperationType.Event:
                result = SendEvent(payload, deliveryMethod.isReliable(), encrypt, channel);
                break;

            case OperationType.Response:
                result = SendResponse(payload, deliveryMethod.isReliable(), encrypt, channel);
                break;

            default:
                return(GladNet.Common.SendResult.Invalid);
            }

            //Map the send result
            switch (result)
            {
            case Photon.SocketServer.SendResult.Ok:
                return(GladNet.Common.SendResult.Sent);

            case Photon.SocketServer.SendResult.Disconnected:
                return(GladNet.Common.SendResult.FailedNotConnected);

            case Photon.SocketServer.SendResult.SendBufferFull:
                return(GladNet.Common.SendResult.Invalid);

            case Photon.SocketServer.SendResult.MessageToBig:
                return(GladNet.Common.SendResult.Invalid);

            case Photon.SocketServer.SendResult.InvalidChannel:
                return(GladNet.Common.SendResult.Invalid);

            case Photon.SocketServer.SendResult.Failed:
                return(GladNet.Common.SendResult.Invalid);

            case Photon.SocketServer.SendResult.InvalidContentType:
                return(GladNet.Common.SendResult.Invalid);

            case Photon.SocketServer.SendResult.EncryptionNotSupported:
                return(GladNet.Common.SendResult.Invalid);

            default:
                return(GladNet.Common.SendResult.Invalid);
            }
        }
        protected override void OnReceiveRequest(PacketPayload payload, IMessageParameters parameters)
        {
            //We're not interested in unencrypted messages on the ProxyLoadBalancing server

            /*if (!parameters.Encrypted)
             *      return;
             * else
             *      Logger.WarnFormat("AuthService: {0} at IP {1} tried to send unencrypted payload Type: {2}", PeerDetails.ConnectionID, PeerDetails.RemoteIP.ToString(), payload.GetType());*/

            Logger.Debug("Recieved a message.");

            //Pass this message to the handlers
            requestHandler.TryProcessPayload(payload, parameters, this);
        }
    //ProgressEvent m_progressEvents = new ProgressEvent();
    //public ProgressEvent progressEvents { get { return m_progressEvents; }}
    
    public async Task UDPing(){

	bool isError = false;
	int  nr      = profile.pps * profile.duration;
	m_isAbort   = false;
      
	profile.BenchStart(PRE_WARM_PACKET_NR);
	
	var startMicroSec = profile.now * 1000;

	var body           = new PacketPayload();
	if(profile.pktPayloadSize > 10){ body.msg = new string('X', profile.pktPayloadSize - 10); }

	var payload        = JsonSerializer.Serialize(body);
	var preWarmCnt     = PRE_WARM_PACKET_NR;

	profile.currentSeq = -preWarmCnt;
	
	for(;profile.currentSeq < nr; ++profile.currentSeq){
	    if(m_isAbort){ break; }
	    	    	    
	    if(preWarmCnt > 0){
		SendTestPacket(MSG_TYPE_ECHO, System.Int32.MaxValue + profile.currentSeq, payload, payload.Length);
		--preWarmCnt;
		if(preWarmCnt == 0){ startMicroSec = profile.now * 1000; }
		
		var waitByMSec = (int)(1000 / profile.pps);
		if(waitByMSec > 0){ await Task.Delay(waitByMSec); }
	    }
	    else {
		SendTestPacket(MSG_TYPE_ECHO, profile.currentSeq, payload, payload.Length);
		profile.SendHandler(profile.currentSeq);

		var deltaMicroSec = 1000000 * (profile.currentSeq + 1) / profile.pps;
		var waitByMSec    = (int)(((startMicroSec + deltaMicroSec) / 1000) - profile.now);
		//UnityEngine.Debug.Log(profile.currentSeq.ToString() + " : " + waitByMSec.ToString());	    
		if(waitByMSec > 0){ await Task.Delay(waitByMSec); }
	    }
	}
	
	// 最終PacketのTimeoutを待つためにWait
	await Task.Delay(TIMEOUT_MSEC);

	profile.BenchEnd();
	
	if     (m_isAbort){ profile.status = Status.E_INTR; }
	else if(isError)  { profile.status = Status.E_CRITICAL; }
	else              { profile.status = Status.E_OK; }	    
    }
        public SendResult SendRequest(PacketPayload payload, DeliveryMethod deliveryMethod, bool encrypt = false, byte channel = 0)
        {
            //We send messages now and not payloads
            RequestMessage message = new RequestMessage(payload);

            //Serialize the internal payload
            //We need to do this manually
            message.Payload.Serialize(serializer);

            //WARNING: Make sure to send encrypted parameter. There was a fault where we didn't. We cannot unit test it as it's within a MonoBehaviour
            return(peer.OpCustom(1, new Dictionary <byte, object>()
            {
                { 1, serializer.Serialize(message) }
            }, deliveryMethod.isReliable(), channel, encrypt) ? SendResult.Sent : SendResult.Invalid);
        }
        public SendResult TrySendMessage(OperationType opType, PacketPayload payload, DeliveryMethod deliveryMethod, bool encrypt = false, byte channel = 0)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            if (!CanSend(opType))
            {
                throw new InvalidOperationException($"Cannot send {opType} with the {this.GetType().Name} because the service cannot handle that {nameof(OperationType)}.");
            }

            INetworkMessage message = networkMessageFactory.Create(opType, payload);

            return(SendValidMessage(message, deliveryMethod, encrypt, channel));
        }
示例#20
0
        protected void Serialize(PacketPayload packetPayload, byte[] expected)
        {
            var stream = new MemoryStream();
            var packet = new Packet
            {
                //SyncCharacters = Constants.SyncCharacters,
                Content = new PacketContent
                {
                    Payload = packetPayload
                }
            };

            Serializer.Serialize(stream, packet);

            AssertEqual(expected, stream.ToArray());
        }
        /// <summary>
        /// Creates a new <see cref="INetworkMessage"/>
        /// </summary>
        /// <param name="opType">Operation type of the message.</param>
        /// <param name="payload">Payload for the <see cref="INetworkMessage"/>.</param>
        /// <returns>A new non-null <see cref="INetworkMessage"/>.</returns>
        public INetworkMessage Create(OperationType opType, PacketPayload payload)
        {
            switch (opType)
            {
            case OperationType.Event:
                return(new EventMessage(payload));

            case OperationType.Request:
                return(new RequestMessage(payload));

            case OperationType.Response:
                return(new ResponseMessage(payload));

            default:
                throw new InvalidOperationException($"Cannot create a {nameof(INetworkMessage)} instance for {nameof(OperationType)}: {opType}.");
            }
        }
示例#22
0
		public SendResult EnqueueRequest(RequestMessage requestMessage)
		{
			if (requestMessage == null) throw new ArgumentNullException(nameof(requestMessage));

			PacketPayload payload = requestMessage.Payload.Data; //reference to save the payload

			requestMessage.Payload.Serialize(serializer); //have to serialize payload first
			byte[] serializedData = serializer.Serialize(requestMessage);

			//This shouldn't happen but if it does we'll want some information on which type failed.
			if (serializedData == null)
				throw new InvalidOperationException($"Payload failed to serialize {requestMessage} of Type: {requestMessage?.Payload?.Data?.GetType()?.Name}.");

			string payloadName = requestMessage.Payload?.Data?.GetType().Name;

			if (payloadName == null)
				throw new InvalidOperationException($"Failed to determine endpoint URL due to invalid or unavailable payload name.");

			return EnqueueRequest(serializedData, payloadName, payload);
		}
 public SendResult SendRequest(PacketPayload payload, DeliveryMethod deliveryMethod, bool encrypt = false, byte channel = 0)
 {
     return(NetworkSendService.TrySendMessage(OperationType.Request, payload, deliveryMethod, encrypt, channel));
 }
 public TestSerialization(PacketPayload payload)
 {
     netsendable = new NetSendable <PacketPayload>(payload);
 }
 public SendResult TrySendMessage(OperationType opType, PacketPayload payload, DeliveryMethod deliveryMethod, bool encrypt = false, byte channel = 0)
 {
     return(CanSend(opType) ? SendRequest(payload, deliveryMethod, encrypt, channel) : SendResult.Invalid);
 }
示例#26
0
 internal RawPacketHandlerEventArgs(MessageId messageId, PacketPayload packetPayload)
 {
     MessageId     = messageId;
     PacketPayload = packetPayload;
 }
示例#27
0
 /// <summary>
 /// Serializes the <see cref="PacketPayload"/> provided.
 /// </summary>
 /// <param name="payload">Payload to serialize.</param>
 /// <returns>The serialized packet payload.</returns>
 private byte[] SerializePayload(PacketPayload payload)
 {
     return(serializerStrategy.Serialize(payload));
 }