Esempio n. 1
0
 private void HandleTestIndexRequest(IWebSocketContext requester)
 {
     // Send a list of the filenames in the Application's local folder
     ApplicationData.Current.LocalFolder.GetFilesAsync().AsTask().ContinueWith((res) =>
     {
         string response;
         if (res.IsFaulted)
         {
             response = JsonConvert.SerializeObject(
                 new Message {
                 Type = Message.MessageType.TestIndexResponse,
                 Data = null
             });
         }
         else
         {
             IReadOnlyList <StorageFile> result = res.Result;
             IEnumerable <string> testNames     = result.Select((a) => a.DisplayName);
             response = JsonConvert.SerializeObject(
                 new Message
             {
                 Type = Message.MessageType.TestIndexResponse,
                 Data = testNames
             });
         }
         Send(requester, response);
     });
 }
        public async Task HandleAsync(
            IWebSocketContext context,
            GenericOperationMessage message,
            CancellationToken cancellationToken)
        {
            ConnectionStatus connectionStatus =
                await context.OpenAsync(message.Payload.ToDictionary())
                .ConfigureAwait(false);

            if (connectionStatus.Accepted)
            {
                await context.SendConnectionAcceptMessageAsync(
                    cancellationToken).ConfigureAwait(false);

                await context.SendConnectionKeepAliveMessageAsync(
                    cancellationToken).ConfigureAwait(false);
            }
            else
            {
                await context.SendConnectionErrorMessageAsync(
                    connectionStatus.Response, cancellationToken)
                .ConfigureAwait(false);

                await context.CloseAsync().ConfigureAwait(false);
            }
        }
Esempio n. 3
0
        protected override async void OnClientConnected(
            IWebSocketContext context,
            System.Net.IPEndPoint localEndPoint,
            System.Net.IPEndPoint remoteEndPoint)
        {
            context.RequestRegexUrlParams("/ws/{token}").TryGetValue("token", out object token);

            bool valid = false;

            try
            {
                valid = await JWTService.Validate(token.ToString(), this.web.secret);
            }
            catch (Exception e)
            {
                this.api.Server.Logger.Warning(e.Message);
            }
            if (valid)
            {
                var response = new IServerAPIToJSON(api.Server);
                var msg      = new WSMessage("Notification", "Websocket server started.");
                Send(context, msg.ToJSON());
                return;
            }
            var err = new WSMessage("Error", "Unauthorized");

            Send(context, err.ToJSON());
            await context.WebSocket.CloseAsync();
        }
Esempio n. 4
0
        protected override Task OnMessageReceivedAsync(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result)
        {
            try
            {
                var req = JsonSerializer.Deserialize <WebsocketRequest>(buffer);

                if (req.RequestPayload.Equals("ping"))
                {
                    return(SendAsync(context, new WebsocketResponse()
                    {
                        ResponseCode = 200, ResponsePayload = "pong"
                    }.ToJson()));
                }
                else if (req.RequestPayload.Equals("cputemp"))
                {
                    var cpuTemps = CpuTempMonitor.GetCpuTemps();
                    return(SendAsync(context, new WebsocketResponse()
                    {
                        ResponseCode = 200, ResponsePayload = cpuTemps
                    }.ToJson()));
                }
            }
            catch (Exception e)
            {
                $"Exception - {e.Message}".Error();
            }
            return(SendAsync(context, new WebsocketResponse()
            {
                ResponseCode = 400, ResponsePayload = "invalid request"
            }.ToJson()));
        }
Esempio n. 5
0
        protected override Task OnMessageReceivedAsync(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result)
        {
            var str = Encoding.GetString(buffer);
            Dictionary <string, object> watchedTokens;

            lock (_lockingObject)
                watchedTokens = watchedTokensPerContext[context.Id];

            lock (watchedTokens)
            {
                watchedTokens.Clear();
                List <string> tokenNames = null;
                try
                {
                    tokenNames = Newtonsoft.Json.JsonConvert.DeserializeObject <List <string> >(str);
                }
                catch (Exception) { }

                if (tokenNames != null && tokenNames.Any())
                {
                    watchedTokens.Clear();
                    foreach (var tokenName in tokenNames)
                    {
                        if (!string.IsNullOrEmpty(tokenName))
                        {
                            watchedTokens[tokenName] = null;
                        }
                    }
                }
            }
            return(Task.CompletedTask);
        }
Esempio n. 6
0
            protected override Task OnClientDisconnectedAsync(IWebSocketContext context)
            {
                var title = StringUtil.GetQueryString(context.RequestUri.Query, "title");

                this.clients.Remove(title);
                return(SendToOthersAsync(context, title + " lefts"));
            }
Esempio n. 7
0
 internal WebSocketPipeline(
     IWebSocketContext context,
     CancellationTokenSource cts)
 {
     _context = context;
     _cts     = cts;
 }
 public async Task HandleAsync(
     IWebSocketContext context,
     GenericOperationMessage message,
     CancellationToken cancellationToken)
 {
     await context.CloseAsync().ConfigureAwait(false);
 }
Esempio n. 9
0
        protected override void OnMessageReceived(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result)
        {
            //TODO: Considering to send data from client side as binary Streamed JSON for performance in the future !
            //TODO: Still, the mismatching CLR type namespace need to be fixed first
            //Value type reference as byte[] and/or string are not good for performance
            string methodProxyJson = buffer.ToText();

            Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
            {
                MethodProxy taksInput  = null;
                MethodProxy taksOutput = null;

                try
                {
                    taksInput  = ContextBridge.GetMethodProxyFromJSON(ref methodProxyJson);
                    taksOutput = await ContextBridge.Receive(taksInput);
                }
                catch (Exception ex)
                {
                    ConsoleHelper.WriteLine("Error: [Native] - BlazorContextBridge.Receive: " + ex.Message);
                }

                try
                {
                    string jsonReturnValue = ContextBridge.GetJSONReturnValue(taksOutput);
                    SendMessageToClient(jsonReturnValue);
                }
                catch (Exception ex)
                {
                    ConsoleHelper.WriteLine("Error: [Native] - BlazorContextBridge.Send: " + ex.Message);
                }
            });
        }
Esempio n. 10
0
        public void AddClient(string groupId, IWebSocketContext client)
        {
            var group = clientGroupsById.GetOrAdd(groupId, id => new ClientGroup(groupId, sender));

            clientsToGroupsMap[client] = group;
            group.AddClient(client);
        }
        protected override Task OnMessageReceivedAsync(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result)
        {
            var str = Encoding.GetString(buffer);
            Dictionary <string, object> watchedKeyValues;

            lock (_lockingObject)
                watchedKeyValues = watchedKeyValuesPerContext[context.Id];

            lock (watchedKeyValues)
            {
                watchedKeyValues.Clear();
                List <string> kvNames = null;
                try
                {
                    kvNames = Newtonsoft.Json.JsonConvert.DeserializeObject <List <string> >(str);
                }
                catch (Exception ex)
                {
                    ex.Log(context.Id);
                }

                if (kvNames != null && kvNames.Any())
                {
                    watchedKeyValues.Clear();
                    foreach (var key in kvNames)
                    {
                        if (!string.IsNullOrEmpty(key))
                        {
                            watchedKeyValues[key] = null;
                        }
                    }
                }
            }
            return(Task.CompletedTask);
        }
        public void Send(IWebSocketContext context, CommMessage message)
        {
            string type = message.GetType().Name;
            string json = Json.Serialize(message);

            _ = SendAsync(context, type + ":" + json);
        }
 protected override Task OnMessageReceivedAsync(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result)
 {
     return(Dispatcher.DoAction(() =>
     {
         CommContext commContext;
         if (!mContextMap.TryGetValue(context, out commContext))
         {
             commContext = null;
         }
         if (commContext != null)
         {
             string json = Encoding.UTF8.GetString(buffer);
             int index = json.IndexOf(":");
             if (index > 0)
             {
                 string type = json.Substring(0, index);
                 json = json.Substring(index + 1);
                 Type t;
                 if (BaseServer.MessageNameToType.TryGetValue(type, out t))
                 {
                     CommMessage message = Json.Deserialize(json, t) as CommMessage;
                     if (message != null)
                     {
                         message.Handle(commContext);
                     }
                 }
             }
         }
     }));
 }
 protected override Task OnClientDisconnectedAsync(IWebSocketContext context)
 {
     return(Dispatcher.DoAction(() =>
     {
         mContextMap.Remove(context);
     }));
 }
Esempio n. 15
0
        protected override Task OnClientConnectedAsync(IWebSocketContext context)
        {
            var task = base.OnClientConnectedAsync(context);

            Task.Run(() => SendLoop(context));
            return(task);
        }
        public async Task HandleAsync(
            IWebSocketContext context,
            GenericOperationMessage message,
            CancellationToken cancellationToken)
        {
            QueryRequest request = message.Payload.ToObject <QueryRequest>();

            IExecutionResult result = await context.QueryExecuter.ExecuteAsync(
                new Execution.QueryRequest(request.Query, request.OperationName)
            {
                VariableValues = QueryMiddlewareUtilities
                                 .DeserializeVariables(request.Variables),
                Services = QueryMiddlewareUtilities
                           .CreateRequestServices(context.HttpContext)
            },
                cancellationToken).ConfigureAwait(false);

            if (result is IResponseStream responseStream)
            {
                context.RegisterSubscription(
                    new Subscription(context, responseStream, message.Id));
            }
            else if (result is IQueryExecutionResult queryResult)
            {
                await context.SendSubscriptionDataMessageAsync(
                    message.Id, queryResult, cancellationToken);

                await context.SendSubscriptionCompleteMessageAsync(
                    message.Id, cancellationToken);
            }
        }
 public Task HandleAsync(
     IWebSocketContext context,
     GenericOperationMessage message,
     CancellationToken cancellationToken)
 {
     context.UnregisterSubscription(message.Id);
     return(Task.CompletedTask);
 }
 protected override void OnMessageReceived(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult)
 {
     foreach (var ws in WebSockets)
     {
         //if (ws != context)
         //  Send(ws, rxBuffer.ToText());
     }
 }
 public Task HandleAsync(
     IWebSocketContext context,
     GenericOperationMessage message,
     CancellationToken cancellationToken)
 {
     context.Dispose();
     return(Task.CompletedTask);
 }
 protected override Task OnClientConnectedAsync(IWebSocketContext context)
 {
     return(Dispatcher.DoAction(() =>
     {
         CommContext commContext = mCommContextFactory.Create(this, context);
         mContextMap[context] = commContext;
     }));
 }
Esempio n. 21
0
 /// <inheritdoc />
 protected override Task OnMessageReceivedAsync(
     IWebSocketContext context,
     byte[] buffer,
     IWebSocketReceiveResult result)
 {
     return(Task.CompletedTask);
     //return SendToOthersAsync(context, Encoding.GetString(buffer));
 }
        protected async override Task OnClientConnectedAsync(IWebSocketContext context)
        {
            await Task.Delay(1000);

            await SendAsync(context, new EventResponse <JobInfo>(_jobService.GetJobs()).ToString());

            await base.OnClientConnectedAsync(context);
        }
Esempio n. 23
0
        /// <inheritdoc />
        protected override Task OnMessageReceivedAsync(
            IWebSocketContext context,
            byte[] rxBuffer,
            IWebSocketReceiveResult rxResult)
        {
            SendToOthersAsync(context, Encoding.GetString(rxBuffer));

            return(null);
        }
        protected override Task OnClientConnectedAsync(IWebSocketContext context)
        {
            var task = base.OnClientConnectedAsync(context);

            lock (_lockingObject)
                watchedKeyValuesPerContext.Add(context.Id, new Dictionary <string, object>());
            Task.Run(() => SendLoop(context));
            return(task);
        }
Esempio n. 25
0
 protected override void OnClientConnected(IWebSocketContext context, System.Net.IPEndPoint localEndPoint, System.Net.IPEndPoint remoteEndPoint)
 {
     // Send the cached level on connect - if available
     if (SMMServer.LastLevelTransmitted != null)
     {
         string message = JsonConvert.SerializeObject(SMMServer.LastLevelTransmitted);
         Send(context, message);
     }
 }
Esempio n. 26
0
 /// <inheritdoc />
 protected override void OnMessageReceived(IWebSocketContext context, byte[] rxBuffer,
                                           IWebSocketReceiveResult rxResult)
 {
     lock (_syncRoot)
     {
         var arg = rxBuffer.ToText();
         _processes[context].StandardInput.WriteLine(arg);
     }
 }
 public SubscriptionReceiver(
     IWebSocketContext webSocket,
     PipeWriter writer,
     CancellationTokenSource cts)
 {
     _webSocket = webSocket;
     _writer    = writer;
     _cts       = cts;
 }
Esempio n. 28
0
        public Client(string contextId, IWebSocketContext context)
        {
            this.ContextId      = contextId;
            this.Context        = context;
            this.MessagesQueues = new ConcurrentDictionary <long, string>();

            //fix
            this._primusPingTimer = new Timer(this.PrimusPing, new AutoResetEvent(false), 5000, 25000);
        }
Esempio n. 29
0
 public WebSocketKeepAlive(
     IWebSocketContext context,
     TimeSpan timeout,
     CancellationTokenSource cts)
 {
     _context = context;
     _timeout = timeout;
     _cts     = cts;
 }
Esempio n. 30
0
        private async Task ProcessSystemWebsocket(
            IWebSocketContext context,
            System.Net.WebSockets.WebSocket webSocket,
            CancellationToken ct)
        {
            // define a receive buffer
            var receiveBuffer = new byte[ReceiveBufferSize];

            // define a dynamic buffer that holds multi-part receptions
            var receivedMessage = new List <byte>(receiveBuffer.Length * 2);

            // poll the WebSockets connections for reception
            while (webSocket.State == System.Net.WebSockets.WebSocketState.Open)
            {
                // retrieve the result (blocking)
                var receiveResult = new WebSocketReceiveResult(await webSocket
                                                               .ReceiveAsync(new ArraySegment <byte>(receiveBuffer), ct).ConfigureAwait(false));

                if (receiveResult.MessageType == (int)System.Net.WebSockets.WebSocketMessageType.Close)
                {
                    // close the connection if requested by the client
                    await webSocket
                    .CloseAsync(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, string.Empty, ct)
                    .ConfigureAwait(false);

                    return;
                }

                var frameBytes = new byte[receiveResult.Count];
                Array.Copy(receiveBuffer, frameBytes, frameBytes.Length);
                OnFrameReceived(context, frameBytes, receiveResult);

                // add the response to the multi-part response
                receivedMessage.AddRange(frameBytes);

                if (receivedMessage.Count > _maximumMessageSize && _maximumMessageSize > 0)
                {
                    // close the connection if message exceeds max length
                    await webSocket.CloseAsync(System.Net.WebSockets.WebSocketCloseStatus.MessageTooBig,
                                               $"Message too big. Maximum is {_maximumMessageSize} bytes.",
                                               ct).ConfigureAwait(false);

                    // exit the loop; we're done
                    return;
                }

                // if we're at the end of the message, process the message
                if (!receiveResult.EndOfMessage)
                {
                    continue;
                }

                OnMessageReceived(context, receivedMessage.ToArray(), receiveResult);
                receivedMessage.Clear();
            }
        }