예제 #1
0
        protected void NotifyServerEventAsync(string clientId, ServerEvents serverEvent, object data)
        {
            serverEventsSubscriptors.TryGetValue(serverEvent, out Dictionary <string, ConnectionCredentials> subscriptors);
            WebsocketDataPackage package = GenerateSignedPackage("API", data);

            if (subscriptors != null)
            {
                if (subscriptors[clientId].ConnectionSet)
                {
                    NotifyToClient(subscriptors[clientId], package);
                }
            }
        }
예제 #2
0
        protected void BroadcastServerEventAsync(ServerEvents serverEvent, object data)
        {
            serverEventsSubscriptors.TryGetValue(serverEvent, out Dictionary <string, ConnectionCredentials> subscriptors);
            WebsocketDataPackage package = GenerateSignedPackage("API", data);

            if (subscriptors != null)
            {
                subscriptors.Values.ToList().ForEach(cc =>
                {
                    if (cc.ConnectionSet)
                    {
                        NotifyToClient(cc, package);
                    }
                });
            }
        }
예제 #3
0
 private static bool NotifyToClient(ConnectionCredentials cc, WebsocketDataPackage package)
 {
     if (clientsConnections.TryGetValue(cc, out Connection connection))
     {
         string jsonData    = JsonConvert.SerializeObject(package);
         Byte[] bytesToSend = System.Text.Encoding.UTF8.GetBytes(jsonData);
         try
         {
             lock (sendLocker)
             {
                 connection.webSocket.SendAsync(new ArraySegment <byte>(bytesToSend),
                                                WebSocketMessageType.Text, true, new CancellationToken());
                 return(true);
             }
         }catch (Exception ex)
         {
             Exception e = ex;
         }
     }
     return(false);
 }
예제 #4
0
        //Asynchronous request handler.
        public async Task WebSocketRequestHandler(WebSocketContext webSocketContext)
        {
            //Gets the current WebSocket object.
            WebSocket webSocket = webSocketContext.WebSocket;

            //check the integrity of the connection

            /*We define a certain constant which will represent
             * size of received data. It is established by us and
             * we can set any value. We know that in this case the size of the sent
             * data is very small.
             */
            const int maxMessageSize = 512;

            //Buffer for received bits.
            var receivedDataBuffer = new ArraySegment <Byte>(new Byte[maxMessageSize]);

            var cancellationToken = new CancellationToken();

            //Checks WebSocket state.
            while (webSocket.State == WebSocketState.Open)
            {
                //Reads data.
                WebSocketReceiveResult webSocketReceiveResult =
                    await webSocket.ReceiveAsync(receivedDataBuffer, cancellationToken);

                bool errorDetected = false;
                //If input frame is cancelation frame, send close command.
                if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close)
                {
                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure,
                                               String.Empty, cancellationToken);
                }
                else
                {
                    byte[] payloadData           = receivedDataBuffer.Array.ToList().GetRange(0, webSocketReceiveResult.Count).ToArray();
                    WebsocketDataPackage package = GetPackage(ref payloadData);

                    string clientWsToken = GetConnectionCredential(package.clientId).HashedKey;

                    if (!CheckDataIntegrity(package.Data, package.HashedKey, clientWsToken))
                    {
                        errorDetected = true;
                        byte[] serializedData    = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(package.Data) + clientWsToken);
                        string receivedHashedKey = Convert.ToBase64String(SHA1.Create().ComputeHash(serializedData));

                        string message =
                            String.Format("Corrupted package: SHA1 received: {0} SHA1 expected: {1}", receivedHashedKey, package.HashedKey);
                        Byte[] bytesToSend = System.Text.Encoding.UTF8.GetBytes(message);

                        //Sends data back.
                        await webSocket.SendAsync(new ArraySegment <byte>(bytesToSend),
                                                  WebSocketMessageType.Text, true, cancellationToken);
                    }

                    if (!errorDetected)
                    {
                        ConnectionCredentials cc = GetConnectionCredential(package.clientId);
                        if (!cc.ConnectionSet)
                        {
                            Connection conn = new Connection(cc, webSocket);
                            BindConnection(GetConnectionCredential(package.clientId), conn);
                        }
                        var newString =
                            String.Format("Hello, package with hashed key: " + package.HashedKey + " validated! Time {0}", DateTime.Now.ToString());
                        Byte[] bytes = System.Text.Encoding.UTF8.GetBytes(newString);

                        //Sends data back.
                        await webSocket.SendAsync(new ArraySegment <byte>(bytes),
                                                  WebSocketMessageType.Text, true, cancellationToken);
                    }
                }
            }
        }