Пример #1
0
        /// <summary>
        /// Called when a client has connected to the server.
        /// </summary>
        /// <param name="socket">The web-socket of the client.</param>
        /// <returns>Awaitable Task.</returns>
        public virtual async Task OnConnected(WebSocket socket)
        {
            WebSocketConnectionManager.AddSocket(socket);

            await SendMessageAsync(socket, new Message()
            {
                Data = WebSocketConnectionManager.GetId(socket)
            }).ConfigureAwait(false);
        }
Пример #2
0
 public async Task SendMessageToAllAsync(Message message)
 {
     foreach (var pair in WebSocketConnectionManager.GetAll())
     {
         if (pair.Value.State == WebSocketState.Open)
         {
             await SendMessageAsync(pair.Value, message);
         }
     }
 }
Пример #3
0
 public async Task InvokeClientMethodToAllAsync(string methodName, params object[] arguments)
 {
     foreach (var pair in WebSocketConnectionManager.GetAll())
     {
         if (pair.Value.State == WebSocketState.Open)
         {
             await InvokeClientMethodAsync(pair.Key, methodName, arguments);
         }
     }
 }
        /// <summary>
        /// Called when a client has connected to the server.
        /// </summary>
        /// <param name="socket">The web-socket of the client.</param>
        /// <param name="context">The http context of the client.</param>
        /// <returns>Awaitable Task.</returns>
        public virtual async Task OnConnected(WebSocket socket, HttpContext context)
        {
            WebSocketConnectionManager.AddSocket(socket);

            await SendMessageAsync(socket, new Message()
            {
                MessageType = MessageType.ConnectionEvent,
                Data        = WebSocketConnectionManager.GetId(socket)
            }).ConfigureAwait(false);
        }
        public async Task SendMessageToGroupAsync(string groupID, Message message)
        {
            var sockets = WebSocketConnectionManager.GetAllFromGroup(groupID);

            if (sockets != null)
            {
                foreach (var socket in sockets)
                {
                    await SendMessageAsync(socket, message);
                }
            }
        }
        public async Task InvokeClientMethodToGroupAsync(string groupID, string methodName, params object[] arguments)
        {
            var sockets = WebSocketConnectionManager.GetAllFromGroup(groupID);

            if (sockets != null)
            {
                foreach (var id in sockets)
                {
                    await InvokeClientMethodAsync(id, methodName, arguments);
                }
            }
        }
Пример #7
0
        public virtual async Task OnResponseAsync(WebSocketConnection socket, string serializedMessage)
        {
            var socketId         = WebSocketConnectionManager.GetId(socket);
            var invocationResult = JsonConvert.DeserializeObject <InvocationResult>(serializedMessage, _jsonSerializerSettings);

            if (_waitingRemoteInvocations.ContainsKey(socketId) && invocationResult.Id > 0)
            {
                if (_waitingRemoteInvocations[socketId].ContainsKey(invocationResult.Id))
                {
                    _waitingRemoteInvocations[socketId][invocationResult.Id].SetResult(invocationResult);
                    // remove the completion source from the waiting list.
                }
                _waitingRemoteInvocations[socketId].Remove(invocationResult.Id);
            }
        }
        public async Task SendMessageToGroupAsync(string groupID, Message message)
        {
            var sockets = WebSocketConnectionManager.GetAllFromGroup(groupID);

            if (sockets != null)
            {
                foreach (var socket in sockets)
                {
                    if (message.Channel == null || message.Channel == string.Empty)
                    {
                        message.Channel = groupID;
                    }
                    await SendMessageAsync(socket, message);
                }
            }
        }
 public async Task SendMessageToAllAsync(Message message)
 {
     foreach (var pair in WebSocketConnectionManager.GetAll())
     {
         try
         {
             if (pair.Value.State == WebSocketState.Open)
             {
                 await SendMessageAsync(pair.Value, message).ConfigureAwait(false);
             }
         }
         catch (WebSocketException e)
         {
             if (e.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely)
             {
                 await OnDisconnected(pair.Value);
             }
         }
     }
 }
 public async Task InvokeClientMethodToAllAsync(string methodName, params object[] arguments)
 {
     foreach (var pair in WebSocketConnectionManager.GetAll())
     {
         try
         {
             if (pair.Value.State == WebSocketState.Open)
             {
                 await InvokeClientMethodAsync(pair.Key, methodName, arguments).ConfigureAwait(false);
             }
         }
         catch (WebSocketException e)
         {
             if (e.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely)
             {
                 await OnDisconnected(pair.Value);
             }
         }
     }
 }
Пример #11
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);
        }
Пример #12
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);
        }
Пример #13
0
        public async Task SendGroupNotifyAsync(string groupID, string methodName, object result)
        {
            // create the method invocation descriptor.
            InvocationDescriptor invocationDescriptor = new InvocationDescriptor {
                MethodName = methodName, Params = result
            };

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

            var sockets = WebSocketConnectionManager.GetAllFromGroup(groupID);

            if (sockets != null)
            {
                foreach (var id in sockets)
                {
                    await SendMessageAsync(id, message);
                }
            }
        }
 /// <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(WebSocket socket)
 {
     await WebSocketConnectionManager.RemoveSocket(WebSocketConnectionManager.GetId(socket)).ConfigureAwait(false);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="WebSocketHandler"/> class.
 /// </summary>
 /// <param name="webSocketConnectionManager">The web socket connection manager.</param>
 /// <param name="methodInvocationStrategy">The method invocation strategy used for incoming requests.</param>
 public WebSocketHandler(WebSocketConnectionManager webSocketConnectionManager, MethodInvocationStrategy methodInvocationStrategy)
 {
     _jsonSerializerSettings.Converters.Insert(0, new PrimitiveJsonConverter());
     WebSocketConnectionManager = webSocketConnectionManager;
     MethodInvocationStrategy   = methodInvocationStrategy;
 }
Пример #16
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.
        }
Пример #17
0
 public WebSocketHandler(WebSocketConnectionManager socketManager)
 {
     this.WebSocketConnectionManager = socketManager;
 }
Пример #18
0
 public IWebSocketReceiver(WebSocketConnectionManager webSocketConnectionManager, ILogger <IWebSocketReceiver> logger)
 {
     _connectionManager = webSocketConnectionManager;
     _logger            = logger;
 }
Пример #19
0
 protected WebSocketHandler(WebSocketConnectionManager webSocketConnectionManager)
 {
     this.WebSocketConnectionManager = webSocketConnectionManager;
 }
 public async Task SendMessageAsync(string socketId, Message message)
 {
     await SendMessageAsync(WebSocketConnectionManager.GetSocketById(socketId), message).ConfigureAwait(false);
 }
Пример #21
0
 public WebSocketHandler(WebSocketConnectionManager webSocketConnectionManager, ILogger <WebSocketHandler> logger)
 {
     WebSocketConnectionManager = webSocketConnectionManager;
     pingTimer   = new Timer(OnPingTimer, null, WebSocket.DefaultKeepAliveInterval, WebSocket.DefaultKeepAliveInterval);
     this.logger = logger;
 }
Пример #22
0
 public WebSocketHandler(WebSocketConnectionManager webSocketConnectionManager)
 {
     WebSocketConnectionManager = webSocketConnectionManager;
 }
Пример #23
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(WebSocket socket)
        {
            await WebSocketConnectionManager.RemoveSocket(WebSocketConnectionManager.GetId(socket)).ConfigureAwait(false);

            // TODO remove from users list and send user disconnected to all
        }