public async Task <T> InvokeClientMethodAsync <T>(string socketId, string methodName, object[] arguments)
        {
            // create the method invocation descriptor.
            InvocationDescriptor invocationDescriptor = new InvocationDescriptor {
                MethodName = methodName, Arguments = arguments
            };

            // generate a unique identifier for this invocation.
            invocationDescriptor.Identifier = Guid.NewGuid();

            // add ourselves to the waiting list for return values.
            TaskCompletionSource <InvocationResult> task = new TaskCompletionSource <InvocationResult>();

            // after a timeout of 60 seconds we will cancel the task and remove it from the waiting list.
            new CancellationTokenSource(1000 * 60).Token.Register(() => { _waitingRemoteInvocations.Remove(invocationDescriptor.Identifier); task.TrySetCanceled(); });
            _waitingRemoteInvocations.Add(invocationDescriptor.Identifier, task);

            // send the method invocation to the client.
            var message = new Message()
            {
                MessageType = MessageType.MethodInvocation, Data = JsonConvert.SerializeObject(invocationDescriptor, _jsonSerializerSettings)
            };

            await SendMessageAsync(socketId, message).ConfigureAwait(false);

            // wait for the return value elsewhere in the program.
            InvocationResult result = await task.Task;

            // ... we just got an answer.

            // if we have completed successfully:
            if (task.Task.IsCompleted)
            {
                // there was a remote exception so we throw it here.
                if (result.Exception != null)
                {
                    throw new Exception(result.Exception.Message);
                }

                // return the value.

                // support null.
                if (result.Result == null)
                {
                    return(default(T));
                }
                // cast anything to T and hope it works.
                return((T)result.Result);
            }

            // if we reach here we got cancelled or alike so throw a timeout exception.
            throw new TimeoutException(); // todo: insert fancy message here.
        }
Example #2
0
        public async Task SendClientErrorAsync(string socketId, string methodName, RemoteException error)
        {
            // create the method invocation descriptor.
            InvocationResult invocationResult = new InvocationResult {
                MethodName = methodName, Exception = error
            };
            WebSocketConnection socket = WebSocketConnectionManager.GetSocketById(socketId);

            if (socket == null)
            {
                return;
            }

            invocationResult.Id = socket.NextCmdId();
            var message = new Message()
            {
                MessageType = MessageType.MethodInvocation,
                Data        = JsonConvert.SerializeObject(invocationResult)
            };

            await SendMessageAsync(socketId, message).ConfigureAwait(false);
        }
        public async Task ReceiveAsync(WebSocket socket, WebSocketReceiveResult result, Message receivedMessage)
        {
            // method invocation request.
            if (receivedMessage.MessageType == MessageType.MethodInvocation)
            {
                // retrieve the method invocation request.
                InvocationDescriptor invocationDescriptor = null;
                try
                {
                    invocationDescriptor = JsonConvert.DeserializeObject <InvocationDescriptor>(receivedMessage.Data, _jsonSerializerSettings);
                    if (invocationDescriptor == null)
                    {
                        return;
                    }
                }
                catch { return; } // ignore invalid data sent to the server.

                // if the unique identifier hasn't been set then the client doesn't want a return value.
                if (invocationDescriptor.Identifier == Guid.Empty)
                {
                    // invoke the method only.
                    try
                    {
                        await MethodInvocationStrategy.OnInvokeMethodReceivedAsync(socket, invocationDescriptor);
                    }
                    catch (Exception)
                    {
                        // we consume all exceptions.
                    }
                }
                else
                {
                    // invoke the method and get the result.
                    InvocationResult invokeResult;
                    try
                    {
                        // create an invocation result with the results.
                        invokeResult = new InvocationResult()
                        {
                            Identifier = invocationDescriptor.Identifier,
                            Result     = await MethodInvocationStrategy.OnInvokeMethodReceivedAsync(socket, invocationDescriptor),
                            Exception  = null
                        };
                    }
                    // send the exception as the invocation result if there was one.
                    catch (Exception ex)
                    {
                        invokeResult = new InvocationResult()
                        {
                            Identifier = invocationDescriptor.Identifier,
                            Result     = null,
                            Exception  = new RemoteException(ex)
                        };
                    }

                    // send a message to the client containing the result.
                    var message = new Message()
                    {
                        MessageType = MessageType.MethodReturnValue,
                        Data        = JsonConvert.SerializeObject(invokeResult, _jsonSerializerSettings)
                    };
                    await SendMessageAsync(socket, message).ConfigureAwait(false);
                }
            }

            // method return value.
            else if (receivedMessage.MessageType == MessageType.MethodReturnValue)
            {
                var invocationResult = JsonConvert.DeserializeObject <InvocationResult>(receivedMessage.Data, _jsonSerializerSettings);
                // find the completion source in the waiting list.
                if (_waitingRemoteInvocations.ContainsKey(invocationResult.Identifier))
                {
                    // set the result of the completion source so the invoke method continues executing.
                    _waitingRemoteInvocations[invocationResult.Identifier].SetResult(invocationResult);
                    // remove the completion source from the waiting list.
                    _waitingRemoteInvocations.Remove(invocationResult.Identifier);
                }
            }
        }
Example #4
0
        public async Task OnReceivedTextAsync(WebSocketConnection socket, string serializedMessage)
        {
            InvocationDescriptor invocationDescriptor = null;

            try
            {
                invocationDescriptor = JsonConvert.DeserializeObject <InvocationDescriptor>(serializedMessage);
                //invocationDescriptor = JsonConvert.DeserializeObject<InvocationDescriptor>(serializedMessage, _jsonSerializerSettings);
                //invocationDescriptor = JsonConvert.DeserializeObject<InvocationDescriptor>(receivedMessage.Data, _jsonSerializerSettings);
                if (invocationDescriptor == null)
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                return;
            } // ignore invalid data sent to the server.
            // method invocation request.
            if (invocationDescriptor.Params != null)
            {
                // retrieve the method invocation request.
                // if the unique identifier hasn't been set then the client doesn't want a return value.
                if (invocationDescriptor.Id == 0)
                {
                    // invoke the method only.
                    try
                    {
                        await MethodInvocationStrategy.OnInvokeMethodReceivedAsync(socket.Id, invocationDescriptor);
                    }
                    catch (Exception)
                    {
                        // we consume all exceptions.
                    }
                }
                else
                {
                    // invoke the method and get the result.
                    InvocationResult invokeResult;
                    try
                    {
                        // create an invocation result with the results.
                        invokeResult = new InvocationResult()
                        {
                            MethodName = invocationDescriptor.MethodName,
                            Id         = invocationDescriptor.Id,
                            Result     = await MethodInvocationStrategy.OnInvokeMethodReceivedAsync(socket.Id, invocationDescriptor),
                            Exception  = null
                        };
                    }
                    // send the exception as the invocation result if there was one.
                    catch (Exception ex)
                    {
                        invokeResult = new InvocationResult()
                        {
                            MethodName = invocationDescriptor.MethodName,
                            Id         = invocationDescriptor.Id,
                            Result     = null,
                            Exception  = new RemoteException(ex)
                        };
                    }

                    string json = JsonConvert.SerializeObject(invokeResult);
                    // send a message to the client containing the result.
                    var message = new Message()
                    {
                        MessageType = MessageType.MethodReturnValue,
                        Data        = json
                                      //Data = JsonConvert.SerializeObject(invokeResult, _jsonSerializerSettings)
                    };
                    await SendMessageAsync(socket, message).ConfigureAwait(false);
                }
            }
            else
            {
                await OnResponseAsync(socket, serializedMessage);
            }
        }