Beispiel #1
0
        public async Task <IOrder> CreateOrder(string clientUsername, DateTime orderDate, Dictionary <uint, uint> productIdQuantityMap, DateTime?deliveryDate)
        {
            string msg = WebSerializer.SerializeWebMessage(WebMessageType.AddOrder, new OrderDTO {
                ClientUsername       = clientUsername,
                OrderDate            = orderDate,
                ProductIdQuantityMap = productIdQuantityMap,
                DeliveryDate         = deliveryDate
            });
            await WebSocketConnection.SendAsync(msg);

            string responseMsg;

            try
            {
                responseMsg = ReadMessage();
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Failed to add order! {e}");
                return(null);
            }
            WebMessageDTO <object> response = WebSerializer.DeserializeWebMessage(responseMsg);

            if (!(response.Data is OrderDTO orderData))
            {
                throw new ApplicationException("Provided order data object is invalid!");
            }

            return(orderData.ToIOrder());
        }
        private async Task WriteAsync(WebSocketConnection ws, Message message)
        {
            string _messageAsString = message.Stringify <Message>();

            Log($"Writing message {_messageAsString}");
            await ws.SendAsync(_messageAsString);
        }
Beispiel #3
0
        public async Task <IClient> CreateClient(string username, string firstName, string lastName, string street, uint streetNumber,
                                                 string phoneNumber)
        {
            string msg = WebSerializer.SerializeWebMessage(WebMessageType.AddClient, new ClientDTO {
                Username     = username,
                FirstName    = firstName,
                LastName     = lastName,
                Street       = street,
                StreetNumber = streetNumber,
                PhoneNumber  = phoneNumber
            });
            await WebSocketConnection.SendAsync(msg);

            string responseMsg;

            try
            {
                responseMsg = ReadMessage();
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Failed to add client! {e}");
                return(null);
            }
            WebMessageDTO <object> response = WebSerializer.DeserializeWebMessage(responseMsg);

            if (!(response.Data is ClientDTO clientData))
            {
                throw new ApplicationException("Provided client data object is invalid!");
            }

            return(clientData.ToIClient());
        }
Beispiel #4
0
        public async Task ConnectToPeersTestMethod()
        {
            WebSocketConnection _connection = null;
            List <string>       _log        = new List <string>();
            Task _server = WebSocketServer.Server(3001, x => { _connection = x; x.onMessage = m => _log.Add($"received message by test WS: {m}"); });
            TestRepositoryNetwork _repository = new TestRepositoryNetwork();

            using (CommunicationEngine _new = new CommunicationEngine(_repository, -1, x => _log.Add(x)))
            {
                Assert.AreEqual <int>(2, _log.Count);
                Assert.IsTrue(_repository.IsCosistent);
                Uri[] _peers = new Uri[] { new Uri("ws://localhost:3001") };
                _new.ConnectToPeers(_peers);
                await Task.Delay(200);

                Assert.IsNotNull(_connection);
                Assert.AreEqual <int>(5, _log.Count);
                Message _requestLast = new Message()
                {
                    data = string.Empty, type = Message.MessageType.QUERY_LATEST
                };
                await _connection.SendAsync(_requestLast.Stringify <Message>());

                await Task.Delay(300);

                Assert.AreEqual <int>(8, _log.Count);
                Assert.IsTrue(_log[7].Contains("received message by test"));
            }
            foreach (string _message in _log.ToArray())
            {
                Debug.WriteLine(_message);
            }
        }
Beispiel #5
0
        private async void PushFromOutputToWebSocket()
        {
            while (true)
            {
                var data = await _output.ReadAsync();

                if (data.IsEmpty)
                {
                    if (_output.Reading.IsCompleted)
                    {
                        break;
                    }
                    _output.Advance(data.End);
                }
                else
                {
                    // note we don't need to create a mask here - is created internally
                    var message = new Message(data, mask: 0, isFinal: true);
                    var send    = _webSocket.SendAsync(WebSocketsFrame.OpCodes.Binary, ref message);
                    // can free up one lock on the data *before* we await...
                    _output.Advance(data.End);
                    await send;
                }
            }
        }
Beispiel #6
0
        public async Task <IProduct> CreateProduct(string name, double price, ProductType productType)
        {
            string msg = WebSerializer.SerializeWebMessage(WebMessageType.AddProduct, new ProductDTO {
                Name        = name,
                Price       = price,
                ProductType = productType
            });
            await WebSocketConnection.SendAsync(msg);

            string responseMsg;

            try
            {
                responseMsg = ReadMessage();
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Failed to add product! {e}");
                return(null);
            }
            WebMessageDTO <object> response = WebSerializer.DeserializeWebMessage(responseMsg);

            if (!(response.Data is ProductDTO productData))
            {
                throw new ApplicationException("Provided product data object is invalid!");
            }

            return(productData.ToIProduct());
        }
Beispiel #7
0
        public async Task TwoWayCommunication_MessagesReceivedAndValid()
        {
            const string             MSG1 = "abcd", MSG2 = "ASDF123", MSG3 = "qwerty", MSG4 = "¹³œæÊÓÆŒ¥£";
            ConcurrentQueue <string> serverMessages = new ConcurrentQueue <string>(), clientMessages = new ConcurrentQueue <string>();

            using AutoResetEvent
                  serverMsgEvent  = new AutoResetEvent(false),
                  clientConnEvent = new AutoResetEvent(false),
                  clientMsgEvent  = new AutoResetEvent(false);
            using ServerWebSocketConnection server = WebSocketServer.CreateServer(TEST_CONNECTION_PORT);
            server.OnMessage += (o, a) => {
                serverMessages.Enqueue(a.Message);
                serverMsgEvent.Set();
            };
            server.OnClientConnected += (o, a) => clientConnEvent.Set();
            _ = Task.Run(server.RunServerLoop);
            using WebSocketConnection client = await WebSocketClient.ConnectAsync(TEST_CONNECTION_URI);

            client.OnMessage += (o, a) => {
                clientMessages.Enqueue(a.Message);
                clientMsgEvent.Set();
            };
            Assert.IsTrue(clientConnEvent.WaitOne(TEST_TIMEOUT));
            await client.SendAsync(MSG1);

            Assert.IsTrue(serverMsgEvent.WaitOne(TEST_TIMEOUT));
            await client.SendAsync(MSG2);

            Assert.IsTrue(serverMsgEvent.WaitOne(TEST_TIMEOUT));
            await server.SendAsync(MSG3);

            Assert.IsTrue(clientMsgEvent.WaitOne(TEST_TIMEOUT));
            await server.SendAsync(MSG4);

            Assert.IsTrue(clientMsgEvent.WaitOne(TEST_TIMEOUT));
            Assert.AreEqual(2, serverMessages.Count);
            Assert.AreEqual(2, clientMessages.Count);
            Assert.IsTrue(serverMessages.TryDequeue(out string msg));
            Assert.AreEqual(MSG1, msg);
            Assert.IsTrue(serverMessages.TryDequeue(out msg));
            Assert.AreEqual(MSG2, msg);
            Assert.IsTrue(clientMessages.TryDequeue(out msg));
            Assert.AreEqual(MSG3, msg);
            Assert.IsTrue(clientMessages.TryDequeue(out msg));
            Assert.AreEqual(MSG4, msg);
        }
Beispiel #8
0
        public async Task SendItems()
        {
            var fakeSocket       = new FakeWebSocket();
            var socketConnection = new WebSocketConnection(fakeSocket);
            await socketConnection.SendAsync("test", CancellationToken.None);

            Assert.IsNotNull(fakeSocket.FakeSendItems.LastOrDefault());
            Assert.AreEqual("test", fakeSocket.FakeSendItems.LastOrDefault());
        }
Beispiel #9
0
        public async Task <HashSet <IProduct> > GetAllProducts()
        {
            await WebSocketConnection.SendAsync(WebSimpleMessageType.GetAllProducts.ToString());

            WebMessageDTO <object> msg = WebSerializer.DeserializeWebMessage(ReadMessage());

            if (!(msg.Data is HashSet <ProductDTO> productData))
            {
                throw new ApplicationException("Provided product data object is invalid!");
            }
            return(new HashSet <IProduct>(productData.Select(p => p.ToIProduct())));
        }
Beispiel #10
0
        public async Task <HashSet <IOrder> > GetAllOrders()
        {
            await WebSocketConnection.SendAsync(WebSimpleMessageType.GetAllOrders.ToString());

            WebMessageDTO <object> msg = WebSerializer.DeserializeWebMessage(ReadMessage());

            if (!(msg.Data is HashSet <OrderDTO> orderData))
            {
                throw new ApplicationException("Provided order data object is invalid!");
            }
            return(new HashSet <IOrder>(orderData.Select(o => o.ToIOrder())));
        }
Beispiel #11
0
        private async Task ServerSetup(WebSocketConnection connection)
        {
            Sockets.Add(connection);
            connection.onMessage = async(data) =>
            {
                Log($"[Message]: {data}");
                await connection.SendAsync(Resolve(data));
            };
            connection.onClose = () =>
            {
                Log($"[Closing connection]: {connection}");
                Sockets.Remove(connection);
            };
            connection.onError = () =>
            {
                Log($"[Error! Closing connection]: {connection}");
                Sockets.Remove(connection);
            };

            Log("[Sending message] Connected");
            await connection.SendAsync("Connected");
        }
Beispiel #12
0
        public async Task <IProduct> GetProduct(uint id)
        {
            string msg = WebSerializer.SerializeWebMessage(WebMessageType.GetProduct, id);
            await WebSocketConnection.SendAsync(msg);

            WebMessageDTO <object> response = WebSerializer.DeserializeWebMessage(ReadMessage());

            if (!(response.Data is ProductDTO productData))
            {
                throw new ApplicationException("Provided product data object is invalid!");
            }

            return(productData.ToIProduct());
        }
Beispiel #13
0
        public async Task <IOrder> GetOrder(uint id)
        {
            string msg = WebSerializer.SerializeWebMessage(WebMessageType.GetOrder, id);
            await WebSocketConnection.SendAsync(msg);

            WebMessageDTO <object> response = WebSerializer.DeserializeWebMessage(ReadMessage());

            if (!(response.Data is OrderDTO orderData))
            {
                throw new ApplicationException("Provided order data object is invalid!");
            }

            return(orderData.ToIOrder());
        }
Beispiel #14
0
        public async Task <IClient> GetClient(string username)
        {
            string msg = WebSerializer.SerializeWebMessage(WebMessageType.GetClient, username);
            await WebSocketConnection.SendAsync(msg);

            WebMessageDTO <object> response = WebSerializer.DeserializeWebMessage(ReadMessage());

            if (!(response.Data is ClientDTO clientData))
            {
                throw new ApplicationException("Provided client data object is invalid!");
            }

            return(clientData.ToIClient());
        }
Beispiel #15
0
        public async Task <bool> RemoveProduct(IProduct product)
        {
            string msg = WebSerializer.SerializeWebMessage(WebMessageType.RemoveProduct, new ProductDTO(product));
            await WebSocketConnection.SendAsync(msg);

            string response = ReadMessage();

            if (WebSerializer.TryParseRequest(response, out WebSimpleMessageType req) && req == WebSimpleMessageType.Success)
            {
                return(true);
            }
            Debug.WriteLine($"Failed to remove product! {response}");
            return(false);
        }
Beispiel #16
0
        public async Task <bool> Update(IOrder order)
        {
            string msg = WebSerializer.SerializeWebMessage(WebMessageType.UpdateOrder, new OrderDTO(order));
            await WebSocketConnection.SendAsync(msg);

            string response = ReadMessage();

            if (WebSerializer.TryParseRequest(response, out WebSimpleMessageType req) && req == WebSimpleMessageType.Success)
            {
                return(true);
            }
            Debug.WriteLine($"Failed to update order! {response}");
            return(false);
        }
Beispiel #17
0
        public override void OnOpened(WebSocketConnection socket)
        {
            Console.WriteLine("Connected socket: " + socket.ID);

            Task.Run(async() =>
            {
                var rand = new Random(Environment.TickCount);
                while (true)
                {
                    string quote = (rand.NextDouble() * 100.0).ToString("0.00");
                    await socket.SendAsync(quote);
                    Thread.Sleep(1000);
                }
            });
        }
Beispiel #18
0
        public static Task SerializeAsync <T, U>(this ISerializer <T> serializer, WebSocketConnection <U> socket, T value)
            where U : WebSocket
        {
            if (serializer is null)
            {
                throw new ArgumentNullException(nameof(serializer));
            }

            if (socket is null)
            {
                throw new ArgumentNullException(nameof(socket));
            }

            var data = serializer.Serialize(value);

            return(socket.SendAsync(data));
        }
Beispiel #19
0
        public static Task SerializeAsync <T, U>(this ISerializer <T> serializer, WebSocketConnection <U> socket, string message, T value)
            where U : WebSocket
        {
            if (serializer is null)
            {
                throw new ArgumentNullException(nameof(serializer));
            }

            if (socket is null)
            {
                throw new ArgumentNullException(nameof(socket));
            }

            if (message is null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            return(socket.SendAsync(message, value, serializer));
        }
        public async Task Invoke(HttpContext context)
        {
            if (context.WebSockets.IsWebSocketRequest)
            {
                if (ValidateOrigin(context))
                {
                    var textSubProtocol = NegotiateSubProtocol(context.WebSockets.WebSocketRequestedProtocols);
                    var webSocketCompressionProvider = _compressionService.NegotiateCompression(context);
                    var webSocket = await context.WebSockets.AcceptWebSocketAsync(textSubProtocol?.SubProtocol);

                    var webSocketConnection = new WebSocketConnection(webSocket, webSocketCompressionProvider, textSubProtocol ?? _options.DefaultSubProtocol, _options.ReceivePayloadBufferSize);

                    webSocketConnection.ReceiveText += async(sender, message) =>
                    {
                        await webSocketConnection.SendAsync(message, CancellationToken.None);
                    };

                    _connectionsService.AddConnection(webSocketConnection);

                    await webSocketConnection.ReceiveMessagesUntilCloseAsync();

                    if (webSocketConnection.CloseStatus.HasValue)
                    {
                        await webSocket.CloseAsync(webSocketConnection.CloseStatus.Value, webSocketConnection.CloseStatusDescription, CancellationToken.None);
                    }

                    _connectionsService.RemoveConnection(webSocketConnection.Id);
                }
                else
                {
                    context.Response.StatusCode = StatusCodes.Status403Forbidden;
                }
            }
            else
            {
                context.Response.StatusCode = StatusCodes.Status400BadRequest;
            }
        }
        private async void Channel_OnReceive(object sender, ChannelReceivedEventArgs e)
        {
            logger?.LogDebug("SCADA client channel starting receive.");

            try
            {
                MbapHeader  header   = MbapHeader.Decode(e.Message);
                RtuPiSystem piSystem = map.GetItem(header.UnitId);

                if (piSystem == null)
                {
                    logger?.LogWarning("SCADA client receive cannot find RTU pi-system.");
                    throw new InvalidOperationException("RTU pi-system was not found.");
                }

                if (!subscribed.Contains(header.UnitId))
                {
                    //subscribe to pi-system for unit id
                    await connection.AddSubscriptionAsync(piSystem.RtuOutputEvent.ToLowerInvariant(), ReceiveOutput);

                    subscribed.Add(header.UnitId);
                }

                byte[] msg = mapper.MapIn(e.Message);
                await connection.SendAsync(piSystem.RtuInputEvent.ToLowerInvariant(), CONTENT_TYPE, msg);

                MbapHeader mheader = MbapHeader.Decode(msg);


                //await connection.Monitor.SendInAsync(ModuleType.VRTU.ToString(), e.Message, mheader.TransactionId);
            }
            catch (Exception ex)
            {
                logger?.LogError($"SCADA client receive error - {ex.Message}");
                OnError?.Invoke(this, new AdapterErrorEventArgs(Id, ex));
            }
        }
Beispiel #22
0
        private async Task ProcessClientMessage(WebSocketConnection connection, string message)
        {
            Console.WriteLine($"{connection}> {message}");
            if (WebSerializer.TryParseRequest(message, out WebSimpleMessageType msgType))
            {
                switch (msgType)
                {
                case WebSimpleMessageType.GetAllClients:
                {
                    string response =
                        WebSerializer.SerializeWebMessage(WebMessageType.ProvideAllClients,
                                                          new HashSet <ClientDTO>(
                                                              (await DataRepository.GetAllClients())
                                                              .Select(c => new ClientDTO(c))));
                    await connection.SendAsync(response);

                    break;
                }

                case WebSimpleMessageType.GetAllProducts:
                {
                    string response =
                        WebSerializer.SerializeWebMessage(WebMessageType.ProvideAllProducts,
                                                          new HashSet <ProductDTO>(
                                                              (await DataRepository.GetAllProducts())
                                                              .Select(p => new ProductDTO(p))));
                    await connection.SendAsync(response);

                    break;
                }

                case WebSimpleMessageType.GetAllOrders:
                {
                    string response =
                        WebSerializer.SerializeWebMessage(WebMessageType.ProvideAllOrders,
                                                          new HashSet <OrderDTO>(
                                                              (await DataRepository.GetAllOrders())
                                                              .Select(o => new OrderDTO(o))));
                    await connection.SendAsync(response);

                    break;
                }
                }
            }
            else
            {
                try
                {
                    WebMessageDTO <object> msgDto = WebSerializer.DeserializeWebMessage(message);
                    switch (msgDto.MessageType)
                    {
                    case WebMessageType.AddClient:
                    {
                        if (msgDto.Data is ClientDTO clt)
                        {
                            IClient client = await DataRepository.CreateClient(
                                clt.Username, clt.FirstName, clt.LastName,
                                clt.Street, clt.StreetNumber, clt.PhoneNumber);

                            if (client == null)
                            {
                                await connection.SendAsync(WebSimpleMessageType.Failure.ToString());
                            }
                            else
                            {
                                ClientDTO newDto = new ClientDTO(client);
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.ProvideClient, newDto));

                                await ServerWebSocketConnection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.AddClient, newDto));
                            }
                        }
                        else
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());
                        }
                        break;
                    }

                    case WebMessageType.UpdateClient:
                    {
                        bool result = false;
                        if (msgDto.Data is ClientDTO clt)
                        {
                            try
                            {
                                result = await DataRepository.Update(clt.ToIClient());
                            }
                            catch (Exception e)
                            {
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.Error, e.ToString()));
                            }
                        }
                        await connection.SendAsync(result
                                                   ?WebSimpleMessageType.Success.ToString()
                                                       : WebSimpleMessageType.Failure.ToString());

                        if (result)
                        {
                            await ServerWebSocketConnection.SendAsync(
                                WebSerializer.SerializeWebMessage(WebMessageType.UpdateClient, msgDto.Data));
                        }

                        break;
                    }

                    case WebMessageType.RemoveClient:
                    {
                        bool result = false;
                        if (msgDto.Data is ClientDTO clt)
                        {
                            try
                            {
                                result = await DataRepository.RemoveClient(clt.ToIClient());
                            }
                            catch (Exception e)
                            {
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.Error, e.ToString()));
                            }
                        }
                        await connection.SendAsync(result
                                                   ?WebSimpleMessageType.Success.ToString()
                                                       : WebSimpleMessageType.Failure.ToString());

                        if (result)
                        {
                            await ServerWebSocketConnection.SendAsync(
                                WebSerializer.SerializeWebMessage(WebMessageType.RemoveClient, msgDto.Data));
                        }

                        break;
                    }

                    case WebMessageType.AddProduct:
                    {
                        if (msgDto.Data is ProductDTO prd)
                        {
                            IProduct product = await DataRepository.CreateProduct(
                                prd.Name, prd.Price, prd.ProductType);

                            if (product == null)
                            {
                                await connection.SendAsync(WebSimpleMessageType.Failure.ToString());
                            }
                            else
                            {
                                ProductDTO newDto = new ProductDTO(product);
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.ProvideProduct, newDto));

                                await ServerWebSocketConnection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.AddProduct, newDto));
                            }
                        }
                        else
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());
                        }
                        break;
                    }

                    case WebMessageType.UpdateProduct:
                    {
                        bool result = false;
                        if (msgDto.Data is ProductDTO prd)
                        {
                            try
                            {
                                result = await DataRepository.Update(prd.ToIProduct());
                            }
                            catch (Exception e)
                            {
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.Error, e.ToString()));
                            }
                        }
                        await connection.SendAsync(result
                                                   ?WebSimpleMessageType.Success.ToString()
                                                       : WebSimpleMessageType.Failure.ToString());

                        if (result)
                        {
                            await ServerWebSocketConnection.SendAsync(
                                WebSerializer.SerializeWebMessage(WebMessageType.UpdateProduct, msgDto.Data));
                        }

                        break;
                    }

                    case WebMessageType.RemoveProduct:
                    {
                        bool result = false;
                        if (msgDto.Data is ProductDTO prd)
                        {
                            try
                            {
                                result = await DataRepository.RemoveProduct(prd.ToIProduct());
                            }
                            catch (Exception e)
                            {
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.Error, e.ToString()));
                            }
                        }
                        await connection.SendAsync(result
                                                   ?WebSimpleMessageType.Success.ToString()
                                                       : WebSimpleMessageType.Failure.ToString());

                        if (result)
                        {
                            await ServerWebSocketConnection.SendAsync(
                                WebSerializer.SerializeWebMessage(WebMessageType.RemoveProduct, msgDto.Data));
                        }

                        break;
                    }

                    case WebMessageType.AddOrder:
                    {
                        if (msgDto.Data is OrderDTO ord)
                        {
                            IOrder order = await DataRepository.CreateOrder(
                                ord.ClientUsername, ord.OrderDate,
                                ord.ProductIdQuantityMap, ord.DeliveryDate);

                            if (order == null)
                            {
                                await connection.SendAsync(WebSimpleMessageType.Failure.ToString());
                            }
                            else
                            {
                                OrderDTO newDto = new OrderDTO(order);
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.ProvideOrder, newDto));

                                await ServerWebSocketConnection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.AddOrder, newDto));
                            }
                        }
                        else
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());
                        }
                        break;
                    }

                    case WebMessageType.UpdateOrder:
                    {
                        bool result = false;
                        if (msgDto.Data is OrderDTO ord)
                        {
                            try
                            {
                                result = await DataRepository.Update(ord.ToIOrder());
                            }
                            catch (Exception e)
                            {
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.Error, e.ToString()));
                            }
                        }
                        await connection.SendAsync(result
                                                   ?WebSimpleMessageType.Success.ToString()
                                                       : WebSimpleMessageType.Failure.ToString());

                        if (result)
                        {
                            await ServerWebSocketConnection.SendAsync(
                                WebSerializer.SerializeWebMessage(WebMessageType.UpdateOrder, msgDto.Data));
                        }

                        break;
                    }

                    case WebMessageType.RemoveOrder:
                    {
                        bool result = false;
                        if (msgDto.Data is OrderDTO ord)
                        {
                            try
                            {
                                result = await DataRepository.RemoveOrder(ord.ToIOrder());
                            }
                            catch (Exception e)
                            {
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.Error, e.ToString()));
                            }
                        }
                        await connection.SendAsync(result
                                                   ?WebSimpleMessageType.Success.ToString()
                                                       : WebSimpleMessageType.Failure.ToString());

                        if (result)
                        {
                            await ServerWebSocketConnection.SendAsync(
                                WebSerializer.SerializeWebMessage(WebMessageType.RemoveOrder, msgDto.Data));
                        }

                        break;
                    }

                    case WebMessageType.GetClient:
                    {
                        if (!(msgDto.Data is string username))
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());

                            break;
                        }
                        IClient client = await DataRepository.GetClient(username);

                        if (client == null)
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());

                            break;
                        }

                        string response = WebSerializer.SerializeWebMessage(WebMessageType.ProvideClient,
                                                                            new ClientDTO(client));

                        await connection.SendAsync(response);

                        break;
                    }

                    case WebMessageType.GetProduct:
                    {
                        if (!(msgDto.Data is uint id))
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());

                            break;
                        }
                        IProduct product = await DataRepository.GetProduct(id);

                        if (product == null)
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());

                            break;
                        }

                        string response = WebSerializer.SerializeWebMessage(WebMessageType.ProvideProduct,
                                                                            new ProductDTO(product));

                        await connection.SendAsync(response);

                        break;
                    }

                    case WebMessageType.GetOrder:
                    {
                        if (!(msgDto.Data is uint id))
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());

                            break;
                        }
                        IOrder order = await DataRepository.GetOrder(id);

                        if (order == null)
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());

                            break;
                        }

                        string response = WebSerializer.SerializeWebMessage(WebMessageType.ProvideOrder,
                                                                            new OrderDTO(order));

                        await connection.SendAsync(response);

                        break;
                    }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Failed to parse message '{message}' from a client! {e}");
                }
            }
        }
Beispiel #23
0
        public async Task MultipleClients_MessagesDistributedProperly()
        {
            const string MSG = "123";
            List <WebSocketConnection> serverSideClients = new List <WebSocketConnection>();
            uint serverMessages = 0U, c1Messages = 0U, c2Messages = 0U, c3Messages = 0U;

            using AutoResetEvent
                  serverMsgEvent  = new AutoResetEvent(false),
                  clientConnEvent = new AutoResetEvent(false),
                  client1MsgEvent = new AutoResetEvent(false),
                  client2MsgEvent = new AutoResetEvent(false),
                  client3MsgEvent = new AutoResetEvent(false);
            using (ServerWebSocketConnection server = WebSocketServer.CreateServer(TEST_CONNECTION_PORT))
            {
                _ = Task.Run(server.RunServerLoop);
                server.OnMessage += (o, a) => {
                    ++serverMessages;
                    serverMsgEvent.Set();
                };
                server.OnClientConnected += (o, a) => {
                    serverSideClients.Add(a.ClientConnection);
                    clientConnEvent.Set();
                };
                using WebSocketConnection client1 = await WebSocketClient.ConnectAsync(TEST_CONNECTION_URI);

                client1.OnMessage += (o, a) => {
                    ++c1Messages;
                    client1MsgEvent.Set();
                };
                Assert.IsTrue(clientConnEvent.WaitOne(TEST_TIMEOUT));
                using WebSocketConnection client2 = await WebSocketClient.ConnectAsync(TEST_CONNECTION_URI);

                client2.OnMessage += (o, a) => {
                    ++c2Messages;
                    client2MsgEvent.Set();
                };
                Assert.IsTrue(clientConnEvent.WaitOne(TEST_TIMEOUT));
                using WebSocketConnection client3 = await WebSocketClient.ConnectAsync(TEST_CONNECTION_URI);

                client3.OnMessage += (o, a) => {
                    ++c3Messages;
                    client3MsgEvent.Set();
                };
                Assert.IsTrue(clientConnEvent.WaitOne(TEST_TIMEOUT));
                await serverSideClients[0].SendAsync(MSG);
                Assert.IsTrue(client1MsgEvent.WaitOne(TEST_TIMEOUT));
                await serverSideClients[1].SendAsync(MSG);
                Assert.IsTrue(client2MsgEvent.WaitOne(TEST_TIMEOUT));
                await serverSideClients[2].SendAsync(MSG);
                Assert.IsTrue(client3MsgEvent.WaitOne(TEST_TIMEOUT));
                await server.SendAsync(MSG);

                Assert.IsTrue(client1MsgEvent.WaitOne(TEST_TIMEOUT));
                Assert.IsTrue(client2MsgEvent.WaitOne(TEST_TIMEOUT));
                Assert.IsTrue(client3MsgEvent.WaitOne(TEST_TIMEOUT));
                await client1.SendAsync(MSG);

                Assert.IsTrue(serverMsgEvent.WaitOne(TEST_TIMEOUT));
                await client2.SendAsync(MSG);

                Assert.IsTrue(serverMsgEvent.WaitOne(TEST_TIMEOUT));
                await client3.SendAsync(MSG);

                Assert.IsTrue(serverMsgEvent.WaitOne(TEST_TIMEOUT));
            }
            Assert.AreEqual(3U, serverMessages);
            Assert.AreEqual(2U, c1Messages);
            Assert.AreEqual(2U, c2Messages);
            Assert.AreEqual(2U, c3Messages);
        }
        public async Task Invoke(HttpContext context)
        {
            if (ValidateOrigin(context))
            {
                if (context.WebSockets.IsWebSocketRequest)
                {
                    WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();

                    if (!context.User.Identity.IsAuthenticated)
                    {
                        // Status Code 1008 PolicyViolation
                        await webSocket.CloseOutputAsync(WebSocketCloseStatus.PolicyViolation,
                                                         "Please login first", CancellationToken.None);

                        return;
                    }

                    WebSocketConnection webSocketConnection = new WebSocketConnection(webSocket, _options.ReceivePayloadBufferSize);

                    async void OnWebSocketConnectionOnNewConnection(object sender, EventArgs message)
                    {
                        await Task.Delay(150);

                        try
                        {
                            var welcomeMessage = new ApiNotificationResponseModel <HeartbeatModel>(new HeartbeatModel(null))
                            {
                                Type = ApiNotificationType.Welcome,
                            };
                            await webSocketConnection.SendAsync(JsonSerializer.Serialize(welcomeMessage,
                                                                                         DefaultJsonSerializer.CamelCase), CancellationToken.None);
                        }
                        catch (WebSocketException)
                        {
                            // if the client is closing the socket the wrong way
                        }
                    }

                    webSocketConnection.NewConnection += OnWebSocketConnectionOnNewConnection;

                    _connectionsService.AddConnection(webSocketConnection);

                    await webSocketConnection.ReceiveMessagesUntilCloseAsync();

                    if (webSocketConnection.CloseStatus.HasValue)
                    {
                        await webSocket.CloseOutputAsync(webSocketConnection.CloseStatus.Value,
                                                         webSocketConnection.CloseStatusDescription, CancellationToken.None);
                    }

                    _connectionsService.RemoveConnection(webSocketConnection.Id);
                }
                else
                {
                    context.Response.StatusCode = StatusCodes.Status400BadRequest;
                }
            }
            else
            {
                context.Response.StatusCode = StatusCodes.Status403Forbidden;
            }
        }
Beispiel #25
0
        private void SendRequestMessage(MESSAGE_TYPE messageType, List <string> value = null)
        {
            // value is a parameters separated by $
            CommunicationType cmd = new CommunicationType(messageType, "", value);

            switch (messageType)
            {
            case MESSAGE_TYPE.GET_MENU_REQ:
                socketConnection.SendAsync(Communication.Serializer.SerializeCommunicationType(cmd));
                break;

            case MESSAGE_TYPE.GET_ACTIVE_ORDERS_REQ:
                socketConnection.SendAsync(Communication.Serializer.SerializeCommunicationType(cmd));
                break;

            case MESSAGE_TYPE.GET_COMPLETED_ORDERS_REQ:
                socketConnection.SendAsync(Communication.Serializer.SerializeCommunicationType(cmd));
                break;

            case MESSAGE_TYPE.GET_ACTIVE_DELIVERIES_REQ:
                socketConnection.SendAsync(Communication.Serializer.SerializeCommunicationType(cmd));
                break;

            case MESSAGE_TYPE.GET_COMPLETED_DELIVERIES_REQ:
                socketConnection.SendAsync(Communication.Serializer.SerializeCommunicationType(cmd));
                break;

            case MESSAGE_TYPE.GET_ALL_CLIENTS_REQ:
                socketConnection.SendAsync(Communication.Serializer.SerializeCommunicationType(cmd));
                break;

            case MESSAGE_TYPE.GET_ORDER_BYID_REQ:
                socketConnection.SendAsync(Communication.Serializer.SerializeCommunicationType(cmd));
                break;

            case MESSAGE_TYPE.GET_DELIVERY_BYID_REQ:
                socketConnection.SendAsync(Communication.Serializer.SerializeCommunicationType(cmd));
                break;

            case MESSAGE_TYPE.CREATE_CLIENT_REQ:
                socketConnection.SendAsync(Communication.Serializer.SerializeCommunicationType(cmd));
                break;

            case MESSAGE_TYPE.CREATE_DISH_REQ:
                socketConnection.SendAsync(Communication.Serializer.SerializeCommunicationType(cmd));
                break;

            case MESSAGE_TYPE.CREATE_ORDER_REQ:
                socketConnection.SendAsync(Communication.Serializer.SerializeCommunicationType(cmd));
                break;

            case MESSAGE_TYPE.COMPLETE_ORDER_REQ:
                socketConnection.SendAsync(Communication.Serializer.SerializeCommunicationType(cmd));
                break;

            case MESSAGE_TYPE.COMPLETE_DELIVERY_REQ:
                socketConnection.SendAsync(Communication.Serializer.SerializeCommunicationType(cmd));
                break;
            }
        }