Пример #1
0
        public async Task SendClientNotifyAsync(string socketId, string methodName, object result)
        {
            // create the method invocation descriptor.
            InvocationDescriptor invocationDescriptor = new InvocationDescriptor {
                MethodName = methodName, Params = result
            };
            WebSocketConnection socket = WebSocketConnectionManager.GetSocketById(socketId);

            if (socket == null)
            {
                return;
            }

            var message = new Message()
            {
                MessageType = MessageType.MethodInvocation,
                Data        = JsonConvert.SerializeObject(invocationDescriptor)
            };

            await SendMessageAsync(socketId, message).ConfigureAwait(false);
        }
Пример #2
0
        private async Task Receive(WebSocketConnection socket, Action <WebSocketReceiveResult, string> handleMessage)
        {
            while (socket.WebSocket.State == WebSocketState.Open)
            {
                ArraySegment <Byte> buffer    = new ArraySegment <byte>(new Byte[1024 * 4]);
                string message                = null;
                WebSocketReceiveResult result = null;
                try
                {
                    using (var ms = new MemoryStream())
                    {
                        do
                        {
                            result = await socket.WebSocket.ReceiveAsync(buffer, CancellationToken.None).ConfigureAwait(false);

                            ms.Write(buffer.Array, buffer.Offset, result.Count);
                        }while (!result.EndOfMessage);

                        ms.Seek(0, SeekOrigin.Begin);

                        using (var reader = new StreamReader(ms, Encoding.UTF8))
                        {
                            message = await reader.ReadToEndAsync().ConfigureAwait(false);
                        }
                    }

                    handleMessage(result, message);
                }
                catch (WebSocketException e)
                {
                    if (e.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely)
                    {
                        socket.WebSocket.Abort();
                    }
                }
            }

            await _webSocketHandler.OnDisconnected(socket);
        }
Пример #3
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);
        }
Пример #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);
            }
        }
Пример #5
0
 /// <summary>
 /// Called when a client has disconnected from the server.
 /// </summary>
 /// <param name="socket">The web-socket of the client.</param>
 /// <returns>Awaitable Task.</returns>
 public virtual async Task OnDisconnected(WebSocketConnection socket)
 {
     await WebSocketConnectionManager.RemoveSocket(WebSocketConnectionManager.GetId(socket)).ConfigureAwait(false);
 }
Пример #6
0
        public async Task <T> InvokeClientMethodAsync <T>(string socketId, string methodName, object[] arguments)
        {
            // create the method invocation descriptor.
            object methodParams = null;

            if (arguments.Length == 1)
            {
                methodParams = arguments[0];
            }
            else
            {
                methodParams = arguments;
            }
            InvocationDescriptor invocationDescriptor = new InvocationDescriptor {
                MethodName = methodName, Params = methodParams
            };
            WebSocketConnection socket = WebSocketConnectionManager.GetSocketById(socketId);

            // generate a unique identifier for this invocation.
            if (socket == null)
            {
                return(default(T));
            }
            invocationDescriptor.Id = socket.NextCmdId(); // 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[socketId].Remove(invocationDescriptor.Id); task.TrySetCanceled(); });
            if (!_waitingRemoteInvocations.ContainsKey(socketId))
            {
                _waitingRemoteInvocations[socketId] = new Dictionary <long, TaskCompletionSource <InvocationResult> >();
            }
            _waitingRemoteInvocations[socketId].Add(invocationDescriptor.Id, task);

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

            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.
        }
Пример #7
0
 public virtual async Task OnReceivedBinaryAsync(WebSocketConnection socket, string receivedMessage)
 {
 }
 public string GetId(WebSocketConnection socket)
 {
     return(_sockets.FirstOrDefault(p => p.Value == socket).Key);
 }
 public void AddSocket(WebSocketConnection socket)
 {
     _sockets.TryAdd(socket.Id, socket);
 }
Пример #10
0
 public void Close(WebSocketConnection socket)
 {
     CloseAsync(socket).Wait();
 }
Пример #11
0
        public async Task CloseAsync(WebSocketConnection socket)
        {
            _sockets.TryRemove(socket.ID, out WebSocketConnection throwAwayValue);

            await socket.CloseAsync();
        }
Пример #12
0
 internal void Add(WebSocketConnection socket)
 {
     _sockets.TryAdd(socket.ID, socket);
     OnOpened(socket);
 }
Пример #13
0
 public virtual void OnMessage(WebSocketConnection socket, ArraySegment <byte> bytes)
 {
 }
Пример #14
0
 public virtual void OnMessage(WebSocketConnection socket, string message)
 {
 }
Пример #15
0
 public virtual void OnClosed(WebSocketConnection socket)
 {
 }
Пример #16
0
 public virtual void OnOpened(WebSocketConnection socket)
 {
 }