Пример #1
0
        internal ConnectionResponse AsResponse(long localClientId)
        {
            switch (this.ResponseCode() + 4)
            {
            case ~NearbyConnectionTypes.ConnectionResponse_ResponseCode.ERROR_INTERNAL:
                return(ConnectionResponse.EndpointNotConnected(localClientId, this.RemoteEndpointId()));

            case NearbyConnectionTypes.ConnectionResponse_ResponseCode.ACCEPTED:
                return(ConnectionResponse.AlreadyConnected(localClientId, this.RemoteEndpointId()));

            case NearbyConnectionTypes.ConnectionResponse_ResponseCode.REJECTED:
                return(ConnectionResponse.NetworkNotConnected(localClientId, this.RemoteEndpointId()));

            case NearbyConnectionTypes.ConnectionResponse_ResponseCode.ACCEPTED | NearbyConnectionTypes.ConnectionResponse_ResponseCode.REJECTED:
                return(ConnectionResponse.InternalError(localClientId, this.RemoteEndpointId()));

            case (NearbyConnectionTypes.ConnectionResponse_ResponseCode) 5:
                return(ConnectionResponse.Accepted(localClientId, this.RemoteEndpointId(), this.Payload()));

            case (NearbyConnectionTypes.ConnectionResponse_ResponseCode) 6:
                return(ConnectionResponse.Rejected(localClientId, this.RemoteEndpointId()));

            default:
                throw new InvalidOperationException("Found connection response of unknown type: " + (object)this.ResponseCode());
            }
        }
        public async Task <ConnectionResponse> ReadAsync()
        {
            var result = await _client.GetAsync(_uriToCheck);

            if (result is null)
            {
                return(ConnectionResponse.Error(
                           new ResponseError($"{nameof(NetworkStatusConnection)}: result was null!")));
            }

            if (!result.IsSuccessStatusCode)
            {
                return(ConnectionResponse.Error(
                           new ResponseError(SensorConnectionConstants.CONNECTION_FAILED_READING)));
            }

            if (result.Content is null)
            {
                return(ConnectionResponse.Valid(string.Empty));
            }

            var content = await result.Content?.ReadAsByteArrayAsync();

            return(ConnectionResponse.Valid(Encoding.ASCII.GetString(content), content));
        }
Пример #3
0
        private void OnConnectionRequest(SyncFilesRequest arg2, ConnectionRequest connectionRequest, HttpRequestEventArgs e)
        {
            try
            {
                var token = Guid.NewGuid();
                _connectionStateManager.Add(connectionRequest.Login, token.ToString());
                var folders = _userTableDataBase.GetAvailableFolders(connectionRequest.Login);

                var response = new ConnectionResponse()
                {
                    Token = token.ToString()
                };

                foreach (var folder in folders)
                {
                    var sharedFolder = new SharedFolder();
                    sharedFolder.Files.AddRange(GetListOfPath(folder));
                    response.Shared_folders.Add(sharedFolder);
                }

                ApiController.SendResponse(e, response);
            }
            catch (Exception exception)
            {
                _logger.Error(() => $"{exception}");
                throw;
            }
        }
Пример #4
0
        /// <summary>
        /// Creates a connected client.
        /// In case credentials are provided, the user will be authenticated and the credentials will be stored in the session.
        /// By providing credentials in the constructor of the apiClient it is not necessary to provide credentials for each individual request.
        /// during the session.
        /// </summary>
        private static Client CreateApiClient(string username = null, string password = null)
        {
            Client apiClient = new Client();

            try
            {
                apiClient.OnDataChanged       += new Client.OnDataChangedHandler(OnDataChanged);
                apiClient.OnConnectionChanged += OnConnectionStateChanged;
                apiClient.OnError             += OnError;

                ConnectOptions options = new ConnectOptions(username, password);

                // Connect and authenticate. By providing credentials to the connectWs method, the credentials will be stored in the session.
                ConnectionResponse connectResponse = apiClient.ConnectWs(WebSocketUrl, options).Result;
                if (connectResponse.Error != null)
                {
                    Console.WriteLine(string.Format("Connect failed: {0}", connectResponse.Error?.First().Message));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occurred during client creation: {0}", ex.Message);
            }
            Console.WriteLine("");
            return(apiClient);
        }
Пример #5
0
        internal ConnectionResponse AsResponse(long localClientId)
        {
            switch (ResponseCode())
            {
            case NearbyConnectionTypes.ConnectionResponse_ResponseCode.ACCEPTED:
                return(ConnectionResponse.Accepted(localClientId, RemoteEndpointId(), Payload()));

            case NearbyConnectionTypes.ConnectionResponse_ResponseCode.ERROR_ENDPOINT_ALREADY_CONNECTED:
                return(ConnectionResponse.AlreadyConnected(localClientId, RemoteEndpointId()));

            case NearbyConnectionTypes.ConnectionResponse_ResponseCode.REJECTED:
                return(ConnectionResponse.Rejected(localClientId, RemoteEndpointId()));

            case NearbyConnectionTypes.ConnectionResponse_ResponseCode.ERROR_ENDPOINT_NOT_CONNECTED:
                return(ConnectionResponse.EndpointNotConnected(localClientId, RemoteEndpointId()));

            case NearbyConnectionTypes.ConnectionResponse_ResponseCode.ERROR_NETWORK_NOT_CONNECTED:
                return(ConnectionResponse.NetworkNotConnected(localClientId, RemoteEndpointId()));

            case NearbyConnectionTypes.ConnectionResponse_ResponseCode.ERROR_INTERNAL:
                return(ConnectionResponse.InternalError(localClientId, RemoteEndpointId()));

            default:
                throw new InvalidOperationException("Found connection response of unknown type: " + ResponseCode());
            }
        }
Пример #6
0
        private async Task ProcessMessage(MessageReceivedEventArgs e)
        {
            try
            {
                var response           = e.Message;
                ConnectionResponse obj = null;

                if (response.Length > 0 && Delay > 0)
                {
                    await Task.Delay(Delay).ConfigureAwait(false);
                }

                try
                {
                    obj = JsonConvert.DeserializeObject <ConnectionResponse>(response, JsonHelper.DefaultJsonSerializerSettings);
                }
                catch (JsonException exc)
                {
                    _logger.LogError(exc, "Failed to deserialize response", response);
                    return;
                }

                _logger.LogTrace("◀ Receive {Message}", response);
                ProcessIncomingMessage(obj);
            }
            catch (Exception ex)
            {
                var message = $"Connection failed to process {e.Message}. {ex.Message}. {ex.StackTrace}";
                _logger.LogError(ex, message);
                Close(message);
            }
        }
        private void ProcessMessage(MessageReceivedEventArgs e)
        {
            try
            {
                string             response = e.Message;
                ConnectionResponse obj      = null;

                try
                {
                    obj = JsonSerializer.Deserialize <ConnectionResponse>(response, JsonHelper.DefaultChromiumJsonSerializerOptions);
                }
                catch (JsonException ex)
                {
                    // _logger.LogError(ex, "Failed to deserialize response", response);
                    System.Diagnostics.Debug.WriteLine($"{ex}: Failed to deserialize response {response}");
                    return;
                }

                // _logger.LogTrace("◀ Receive {Message}", response);
                ProcessIncomingMessage(obj);
            }
            catch (Exception ex)
            {
                string message = $"Connection failed to process {e.Message}. {ex.Message}. {ex.StackTrace}";

                // _logger.LogError(ex, message);
                System.Diagnostics.Debug.WriteLine(message);
                Close(message);
            }
        }
Пример #8
0
 public void ShowError(ConnectionResponse response, bool showError = false)
 {
     if (response != null)
     {
         if (!response.IsSuccessful)
         {
             if (response.HasError)
             {
                 if (showError)
                 {
                     MainThreadUtility.InvokeOnMain(() => {
                         //AlertUtility.ShowAppError(response.ErrorBody);
                     });
                 }
             }
             else
             {
                 this.ShowError(StringLiterals.ConnectionError);
             }
         }
     }
     else
     {
         this.ShowError(StringLiterals.ConnectionError);
     }
 }
Пример #9
0
        /// <summary>
        /// Called when the nearby connection response from
        /// sending Remote connection request to the room advertiser.
        /// </summary>
        /// <param name="response">Response.</param>
        internal void OnRoomJoined(ConnectionResponse response)
        {
            Debug.Log("OnRoomJoined Called status: " + response.ResponseStatus);
            if (response.ResponseStatus == ConnectionResponse.Status.Accepted)
            {
                // if we are connected, stop looking for rooms.
                NearbyRoom.StopRoomDiscovery();

                // the first payload is sent with the response so we can initialize
                // the game scene.
                OnMessageReceived(Room.Address, response.Payload);
                connected = true;
            }
            else if (response.ResponseStatus == ConnectionResponse.Status.ErrorAlreadyConnected)
            {
                // cleanup the old connection and join again.
                Room.Disconnect();
                PlayerInfo localPlayer = PlayerInfo.LocalPlayer;
                Room.JoinRoom(
                    localPlayer.Player,
                    localPlayer.SerializedData,
                    OnRoomJoined);
            }
            else
            {
                GameOver("Error joining room: " + response.ResponseStatus);
            }
        }
Пример #10
0
        internal void OnMessage(ConnectionResponse obj)
        {
            var id = obj.Id;

            if (id.HasValue && _callbacks.TryRemove(id.Value, out var callback))
            {
                if (obj.Error != null)
                {
                    callback.TaskWrapper.TrySetException(new MessageException(callback, obj.Error));
                }
                else
                {
                    callback.TaskWrapper.TrySetResult(obj.Result);
                }
            }
            else
            {
                var method = obj.Method;
                var param  = obj.Params?.ToObject <ConnectionResponseParams>();

                MessageReceived?.Invoke(this, new MessageEventArgs
                {
                    MessageID   = method,
                    MessageData = obj.Params
                });
            }
        }
Пример #11
0
        private void ProcessIncomingMessage(ConnectionResponse obj)
        {
            if (!obj.Params.HasValue)
            {
                GetSession(obj.SessionId ?? string.Empty)?.OnMessage(obj);
                return;
            }

            var param = ChromiumProtocolTypes.ParseEvent(obj.Method, obj.Params.Value.GetRawText());

            if (obj.Id == BrowserCloseMessageId)
            {
                return;
            }

            if (param is TargetAttachedToTargetChromiumEvent targetAttachedToTarget)
            {
                string          sessionId = targetAttachedToTarget.SessionId;
                ChromiumSession session   = new ChromiumSession(this, targetAttachedToTarget.TargetInfo.GetTargetType(), sessionId);
                _asyncSessions.AddItem(sessionId, session);
            }
            else if (param is TargetDetachedFromTargetChromiumEvent targetDetachedFromTarget)
            {
                string sessionId = targetDetachedFromTarget.SessionId;
                if (_sessions.TryRemove(sessionId, out var session) && !session.IsClosed)
                {
                    session.OnClosed(targetDetachedFromTarget.InternalName);
                }
            }

            GetSession(obj.SessionId ?? string.Empty).OnMessageReceived(param);
        }
        void SendFrameData(int connectionID)
        {
            ConnectionResponse responseToSend = responses[connectionID].Peek();
            // Use up to 190 bytes from the response
            MIDIFrame mf = new MIDIFrame();

            // nullref here due to response queue being emptied on other thread
            mf.AddHeader2(responseToSend.connectionID, responseToSend.data[responseToSend.bytesSent++], flipFlop);
            totalBytesCount--;
            flipFlop = !flipFlop;

            // Add up to 199 bytes from the active response to an array of data to send
            byte[] bytesToAdd      = new byte[199];
            int    bytesLeftToSend = responseToSend.data.Length - responseToSend.bytesSent;
            int    bytesToAddCount = Math.Min(bytesLeftToSend, 199); // In case there's less than 199 bytes left to send

            Array.Copy(responseToSend.data, responseToSend.bytesSent, bytesToAdd, 0, bytesToAddCount);
            mf.Add199Bytes(bytesToAdd);
            responseToSend.bytesSent += bytesToAddCount;
            totalBytesCount          -= bytesToAddCount;

            // Remove response if all bytes have been sent
            if (responseToSend.bytesSent == responseToSend.data.Length)
            {
                responses[connectionID].Dequeue();
                responsesCount--;
            }

            mf.Send(port);
            GameIsReady = false;
            lastFrame   = mf;
        }
Пример #13
0
        private void ProcessIncomingMessage(ConnectionResponse obj)
        {
            var method = obj.Method;
            var param  = obj.Params.ToObject <ConnectionResponseParams>();

            if (method == "Target.receivedMessageFromTarget")
            {
                var sessionId = param.SessionId;
                if (_sessions.TryGetValue(sessionId, out var session))
                {
                    session.OnMessage(param.Message);
                }
            }
            else if (method == "Target.detachedFromTarget")
            {
                var sessionId = param.SessionId;
                if (_sessions.TryRemove(sessionId, out var session) && !session.IsClosed)
                {
                    session.Close("Target.detachedFromTarget");
                }
            }
            else
            {
                MessageReceived?.Invoke(this, new MessageEventArgs
                {
                    MessageID   = method,
                    MessageData = obj.Params
                });
            }
        }
Пример #14
0
    private IUnityTask OnConnectionRequest(ConnectionRequest connectionRequest, IPEndPoint senderAddress)
    {
        if (IsPlayerConnected(senderAddress) || IsFull)
        {
            return(EmptyTask);
        }

        //TODO (Optimization) Send whole player data only once and then send only meditation value
        var newPlayer = new PlayerData {
            Meditation = 0f, Name = connectionRequest.PlayerName
        };

        _connectedPlayers.Add(senderAddress, newPlayer);

        if (!IsFull)
        {
            var response     = new ConnectionResponse();
            var responseTask = new Common.SendMessageTask(_connection, response, senderAddress);
            return(responseTask);
        }

        var opponentData = GetAnotherPlayer(newPlayer);

        var connectionResponse = new ConnectionResponse(opponentData.Value);
        var sendToPlayer       = new Common.SendMessageTask(_connection, connectionResponse, senderAddress);
        var sendToOpponent     = new Common.SendMessageTask(_connection, newPlayer, opponentData.Key);
        var fireEvent          = new FireEventTask(matchCreated);

        return(new BatchTask(sendToOpponent, sendToPlayer, fireEvent));
    }
Пример #15
0
        public void MustDisconnectCorrectly()
        {
            var proxy = new Mock <IProxyObject>();
            var connectionResponse = new ConnectionResponse
            {
                CommunicationToken    = Guid.NewGuid(),
                ConnectionEstablished = true
            };
            var disconnectionResponse = new DisconnectionResponse
            {
                ConnectionTerminated = true
            };

            proxy.Setup(p => p.Connect(It.IsAny <Guid>())).Returns(connectionResponse);
            proxy.Setup(p => p.Disconnect(It.IsAny <DisconnectionMessage>())).Returns(disconnectionResponse);
            proxy.Setup(o => o.State).Returns(CommunicationState.Opened);
            proxyObjectFactory.Setup(f => f.CreateObject(It.IsAny <string>())).Returns(proxy.Object);

            var token        = Guid.NewGuid();
            var connected    = sut.Connect(token);
            var disconnected = sut.Disconnect();

            proxy.Verify(p => p.Disconnect(It.Is <DisconnectionMessage>(m => m.CommunicationToken == connectionResponse.CommunicationToken)), Times.Once);

            Assert.IsTrue(connected);
            Assert.IsTrue(disconnected);
        }
Пример #16
0
    void callback(ConnectionResponse c)
    {
        switch (c.status)
        {
        case "AUTH":
        {
            verify();
            break;
        }

        case "SUCCESS":
        {
            //Move to ARgorithm Cloud Menu
            Mainmenu.SetActive(false);
            ArgorithmCloudMenu.SetActive(true);
            break;
        }

        default:
        {
            //Alert the user for Error!!
            AlertMain("Connection Error");
            break;
        }
        }
    }
Пример #17
0
        /// <summary>
        /// Is called if the connection attempt resulted in a failure the remote connection point was unreachable or did not respond.
        /// </summary>
        /// <param name="response">Response information that may have been gathered upon the failure.</param>
        protected virtual void OnConnectionFailure(ConnectionResponse response)
        {
#if DEBUGBUILD
            //TODO: Add information to the debug logger string for the response.
            ClassLogger.LogDebug("Failed to connect to a server.");
#endif
            //Just fail silently if not overidden.
        }
Пример #18
0
    /// <summary>
    /// Clear last error message if any. Close network connection to server if open. Connect to game server and send authorize request.
    /// </summary>
    private void Connect(short context)
    {
        Debug.Log("ServerIPEndpoint: " + serverEndpoint.ToString());
        connection = new ServerConnection(serverEndpoint, gameID, version);
        connection.disconnectedCallback = OnNetDisconnected;
        lastError = "";
        try
        {
            connection.Disconnect(true);
            response = connection.Connect(context, new Player {
                username = username, password = password
            });
            handshakeDone = response.connectionSuccess;
            myPlayer      = (Player)response.responseCommand;

            switch (response.responseContext)
            {
            case NetworkCommands.AUTHORIZE_RESPONSE_OK:
                Debug.Log(myPlayer.playerId);
                if (!passwords.ContainsKey(username))
                {
                    passwords.Add(username, password);
                    SavePasswords();
                }
                Application.LoadLevel("Game");
                break;

            case NetworkCommands.AUTHORIZE_RESPONSE_FAIL:
                lastError = "Login failed!";
                break;

            case NetworkCommands.REGISTER_RESPONSE_FAIL:
                lastError = ((PlayerRegisterResponse)response.responseCommand).result.ToString();
                break;

            case CommandCodes.HANDSHAKE_FAILURE:
                lastError = ((ClosedConnectionInfo)response.responseCommand).reason.ToString();
                break;

            case NetworkCommands.AUTHORIZE_GUEST_SUCESSFUL:
                myPlayer = (Player)response.responseCommand;
                Application.LoadLevel("Game");
                break;

            default:
                throw new Exception("Unsupported message code " + response.responseContext.ToString());
            }
            if (!handshakeDone)
            {
                Debug.Log(lastError);
                return;
            }
        }
        catch (Exception e)
        {
            Debug.Log(string.Format("Error occured during connection! Error: {0}", e.Message));
        }
    }
Пример #19
0
        public override void Call(ConnectionRequest packet, IUser sender, IServerManager manager)
        {
            var p = new ConnectionResponse
            {
                IsConnected = packet.IsConnect
            };

            sender.Connector.Send(p);
        }
Пример #20
0
        internal void OnMessage(Guid clientId, MessageContainer container)
        {
            if (!_connections.TryGetValue(clientId, out WsConnection connection))
            {
                return;
            }

            switch (container.Identifier)
            {
            case nameof(ConnectionRequest):
                var connectionRequest  = ((JObject)container.Payload).ToObject(typeof(ConnectionRequest)) as ConnectionRequest;
                var connectionResponse = new ConnectionResponse
                {
                    Result    = ResultCode.Ok,
                    IsSuccess = true,
                };
                if (_connections.Values.Any(c => c.Username == connectionRequest.Username))
                {
                    string reason = $"User '{connectionRequest.Username}' is already logged in.";
                    connectionResponse.Result    = ResultCode.Failure;
                    connectionResponse.IsSuccess = false;
                    connectionResponse.Reason    = reason;
                    connection.Send(connectionResponse.GetContainer());
                    ErrorReceived?.Invoke(this, new ErrorReceivedEventArgs(reason, DateTime.Now));
                }
                else
                {
                    connection.Username            = connectionRequest.Username;
                    connectionResponse.ActiveUsers = _connections.Where(c => c.Value.Username != null).Select(u => u.Value.Username).ToList();
                    connection.Send(connectionResponse.GetContainer());
                    ConnectionStateChanged?.Invoke(this, new ConnectionStateChangedEventArgs(connection.Username, true, DateTime.Now));
                    ConnectionReceived?.Invoke(this, new ConnectionReceivedEventArgs(connection.Username, true, DateTime.Now));
                }
                break;

            case nameof(MessageRequest):
                var messageRequest = ((JObject)container.Payload).ToObject(typeof(MessageRequest)) as MessageRequest;
                MessageReceived?.Invoke(this, new MessageReceivedEventArgs(connection.Username, messageRequest.Target, messageRequest.Message, messageRequest.Groupname, DateTime.Now));
                break;

            case nameof(FiltrationRequest):
                var filtrationRequest = ((JObject)container.Payload).ToObject(typeof(FiltrationRequest)) as FiltrationRequest;
                FiltrationReceived?.Invoke(this, new FiltrationReceivedEventArgs(connection.Username, filtrationRequest.FirstDate, filtrationRequest.SecondDate, filtrationRequest.EventType));
                break;

            case nameof(CreateGroupRequest):
                var createGroupRequest = ((JObject)container.Payload).ToObject(typeof(CreateGroupRequest)) as CreateGroupRequest;
                createGroupRequest.UserList.Add(connection.Username);
                GroupCreated?.Invoke(this, new GroupCreatedEventArgs(createGroupRequest.Groupname, createGroupRequest.UserList));
                break;

            case nameof(LeaveGroupRequest):
                var leaveGroupRequest = ((JObject)container.Payload).ToObject(typeof(LeaveGroupRequest)) as LeaveGroupRequest;
                GroupLeaved?.Invoke(this, new GroupLeavedEventArgs(connection.Username, leaveGroupRequest.Groupname));
                break;
            }
        }
        public void SendFrameIfDataAvailable(bool ACK)
        {
            // If RDY was received when an ACK was expected, it means the frame was dropped
            // and needs to be retransmitted.  Otherwise, mark the last frame as received.
            if (lastFrame != null)
            {
                if (ACK)
                {
                    lastFrame = null;
                }
                else
                {
                    lastFrame.Send(port);
                    GameIsReady = false;
                    return;
                }
            }

            // Send priority ping response if available, or a frame if a connection response is ready
            if (pong != null)
            {
                ConnectionResponse responseToSend = pong;
                MIDIFrame          mf             = new MIDIFrame();
                mf.AddHeader2(responseToSend.connectionID, responseToSend.data[responseToSend.bytesSent++], flipFlop);
                flipFlop = !flipFlop;
                // Add up to 199 bytes from the active response to an array of data to send
                byte[] bytesToAdd      = new byte[199];
                int    bytesLeftToSend = responseToSend.data.Length - responseToSend.bytesSent;
                int    bytesToAddCount = Math.Min(bytesLeftToSend, 199); // In case there's less than 199 bytes left to send
                Array.Copy(responseToSend.data, responseToSend.bytesSent, bytesToAdd, 0, bytesToAddCount);
                mf.Add199Bytes(bytesToAdd);
                pong = null;
                mf.Send(port);
                GameIsReady = false;
                lastFrame   = mf;
            }
            else if (responses[255].Count > 0)
            {
                // Prioritize the loopback connection second
                SendFrameData(255);
            }
            else if (responsesCount > 0)
            {
                // Round robin the rest of the responses
                do
                {
                    connectionIndex++;
                    if (connectionIndex == MAX_USABLE_CONNECTIONS)
                    {
                        connectionIndex = 0;
                    }
                }while (responses[connectionIndex].Count == 0);

                SendFrameData(connectionIndex);
            }
        }
Пример #22
0
        /// <summary>
        /// Dispatches the command to the client control port and produces a <typeparamref name="T" /> response result.
        /// </summary>
        /// <param name="connection">The control connection where the command should be dispatched.</param>
        /// <returns>
        /// A <typeparamref name="T" /> object instance containing the response data.
        /// </returns>
        protected override CommandResponse Dispatch(Connection connection)
        {
            if (connection.Write("signal newnym"))
            {
                ConnectionResponse response = connection.Read();
                return(new CommandResponse(response.Success));
            }

            return(new CommandResponse(false));
        }
Пример #23
0
        private void ProcessIncomingMessage(ConnectionResponse obj)
        {
            if (obj.Id == BrowserCloseMessageId)
            {
                return;
            }

            IFirefoxEvent param = null;

            if (obj.Params?.ValueKind == JsonValueKind.Object)
            {
                param = FirefoxProtocolTypes.ParseEvent(obj.Method, obj.Params.Value.GetRawText());
                if (param is TargetAttachedToTargetFirefoxEvent targetAttachedToTarget)
                {
                    string sessionId = targetAttachedToTarget.SessionId;
                    var    session   = new FirefoxSession(this, targetAttachedToTarget.TargetInfo.Type.ToString(), sessionId, (id, request) =>
                                                          RawSendAsync(new ConnectionRequest
                    {
                        Id        = id,
                        Method    = request.Command,
                        Params    = request,
                        SessionId = sessionId,
                    }));
                    _asyncSessions.AddItem(sessionId, session);
                }
                else if (param is TargetDetachedFromTargetFirefoxEvent targetDetachedFromTarget)
                {
                    string sessionId = targetDetachedFromTarget.SessionId;
                    if (_sessions.TryRemove(sessionId, out var session))
                    {
                        session.OnClosed(targetDetachedFromTarget.InternalName);
                    }
                }
            }

            if (obj.SessionId != null)
            {
                GetSession(obj.SessionId)?.OnMessage(obj);
            }
            else if (obj.Id.HasValue && _callbacks.TryRemove(obj.Id.Value, out var callback))
            {
                if (obj.Error != null)
                {
                    callback.TaskWrapper.TrySetException(new MessageException(callback, obj.Error));
                }
                else
                {
                    callback.TaskWrapper.TrySetResult(FirefoxProtocolTypes.ParseResponse(callback.Method, obj.Result?.GetRawText()));
                }
            }
            else if (param != null)
            {
                MessageReceived?.Invoke(this, param);
            }
        }
Пример #24
0
        private async void Transport_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            try
            {
                var response           = e.Message;
                ConnectionResponse obj = null;

                if (response.Length > 0 && Delay > 0)
                {
                    await Task.Delay(Delay).ConfigureAwait(false);
                }

                try
                {
                    obj = JsonConvert.DeserializeObject <ConnectionResponse>(response, JsonHelper.DefaultJsonSerializerSettings);
                }
                catch (JsonException exc)
                {
                    _logger.LogError(exc, "Failed to deserialize response", response);
                    return;
                }

                _logger.LogTrace("◀ Receive {Message}", response);

                var id = obj.Id;

                if (id.HasValue)
                {
                    //If we get the object we are waiting for we return if
                    //if not we add this to the list, sooner or later some one will come for it
                    if (_callbacks.TryRemove(id.Value, out var callback))
                    {
                        if (obj.Error != null)
                        {
                            callback.TaskWrapper.TrySetException(new MessageException(callback, obj.Error));
                        }
                        else
                        {
                            callback.TaskWrapper.TrySetResult(obj.Result);
                        }
                    }
                }
                else
                {
                    ProcessIncomingMessage(obj);
                }
            }
            catch (Exception ex)
            {
                var message = $"Connection failed to process {e.Message}. {ex.Message}. {ex.StackTrace}";
                _logger.LogError(ex, message);
                Close(message);
            }
        }
 private static void HandleAsyncMessage(MessageTask callback, ConnectionResponse obj)
 {
     if (obj.Error != null)
     {
         callback.TaskWrapper.TrySetException(new MessageException(callback, obj.Error));
     }
     else
     {
         callback.TaskWrapper.TrySetResult(obj.Result);
     }
 }
Пример #26
0
        public static void CheckConnectionResponse(byte[] responseBytes, int expectedLength, Status expectedStatus, string expectedMessage, int expectedIdLength)
        {
            Assert.AreEqual(expectedLength, responseBytes.Length);
            var response            = new ConnectionResponse();
            var codedResponseStream = new CodedInputStream(responseBytes);

            codedResponseStream.ReadMessage(response);
            Assert.AreEqual(expectedStatus, response.Status);
            Assert.AreEqual(expectedMessage, response.Message);
            Assert.AreEqual(expectedIdLength, response.ClientIdentifier.Length);
        }
Пример #27
0
        private void ClientRegistration(WsConnection connection, MessageContainer container)
        {
            var connectionRequest  = ((JObject)container.Payload).ToObject(typeof(ConnectionRequest)) as ConnectionRequest;
            var connectionResponse = new ConnectionResponse
            {
                Result = ResultCodes.Ok
            };

            if (connectionRequest == null)
            {
                return;
            }

            if (_connections.Values.Any(item => item.Login == connectionRequest.Login))
            {
                connectionResponse.Result = ResultCodes.Failure;
                connectionResponse.Reason = $"Client named '{connectionRequest.Login}' is already connected.";
                connection.Send(connectionResponse.GetContainer());
            }
            else
            {
                connection.Login = connectionRequest.Login;
                _connections.TryAdd(connection.Login, connection);

                connection.Send(connectionResponse.GetContainer());
                _clientsNotActiveList.Remove(connection.Login);

                SendUpdatedClientsList(new UpdatedClientsResponse(_connections.Keys, GetNotActiveClientsList()));
                _clientsActivity.TryAdd(connection.Login, new ClientActivity(connection.Login));

                _eventDataBase.Create(
                    new EventDto
                {
                    Date    = DateTime.Now,
                    Message = $"Client {connection.Login} connected"
                });

                List <string> dataBaseListLoginsString = GetDataBaseClientsListToString();

                if (!dataBaseListLoginsString.Contains(connection.Login))
                {
                    _clientDataBase.Create(
                        new ClientDto
                    {
                        Login = connection.Login
                    });
                }

                SendUpdatedDataBaseClientsResponse();
                SendUpdatedDataBaseMsgResponse();
                SendUpdatedDataBaseEventsResponse();
            }
        }
        public async Task SensorWithValidConnectionShouldReturnValidReading()
        {
            var networkConnectionMock = new Mock <ISensorConnection>();

            networkConnectionMock.Setup(connection => connection.ReadAsync())
            .ReturnsAsync(ConnectionResponse.Valid("Message!"));
            var sensor = new ConnectionSensor(networkConnectionMock.Object);

            var reading = await sensor.ReadAsync();

            Assert.True(reading.IsValid);
        }
Пример #29
0
        private void ProcessIncomingMessage(ConnectionResponse obj)
        {
            var method = obj.Method;
            var param  = obj.Params?.ToObject <ConnectionResponseParams>();

            if (method == "Target.attachedToTarget")
            {
                var sessionId = param.SessionId;
                var session   = new CDPSession(this, param.TargetInfo.Type, sessionId);
                _asyncSessions.AddItem(sessionId, session);

                SessionAttached?.Invoke(this, new SessionAttachedEventArgs {
                    Session = session
                });

                if (obj.SessionId != null && _sessions.TryGetValue(obj.SessionId, out var parentSession))
                {
                    parentSession.OnSessionAttached(session);
                }
            }
            else if (method == "Target.detachedFromTarget")
            {
                var sessionId = param.SessionId;
                if (_sessions.TryRemove(sessionId, out var session) && !session.IsClosed)
                {
                    session.Close("Target.detachedFromTarget");
                }
            }

            if (!string.IsNullOrEmpty(obj.SessionId))
            {
                var session = GetSession(obj.SessionId);
                session?.OnMessage(obj);
            }
            else if (obj.Id.HasValue)
            {
                // If we get the object we are waiting for we return if
                // if not we add this to the list, sooner or later some one will come for it
                if (_callbacks.TryRemove(obj.Id.Value, out var callback))
                {
                    MessageQueue.Enqueue(callback, obj);
                }
            }
            else
            {
                MessageReceived?.Invoke(this, new MessageEventArgs
                {
                    MessageID   = method,
                    MessageData = obj.Params
                });
            }
        }
        public async Task SensorWithInvalidConnectionShouldReturnInvalidReading()
        {
            var networkConnectionMock = new Mock <ISensorConnection>();

            networkConnectionMock.Setup(connection => connection.ReadAsync())
            .ReturnsAsync(ConnectionResponse.Error(
                              new ResponseError(SensorConnectionConstants.CONNECTION_FAILED_READING)));
            var sensor = new ConnectionSensor(networkConnectionMock.Object);

            var reading = await sensor.ReadAsync();

            Assert.False(reading.IsValid);
        }
Пример #31
0
	/*
	 * This is the connection response handler from ES
	 * it determines whether success or not and fires off
	 * a login request is successful
	 */
	private void OnConnect(ConnectionResponse response){
        _es.Engine.ConnectionResponse -= OnConnect;
	
		if (response.Successful){
			
			Debug.Log("Connected");
            waitingMessage = "Connected";
			
			// Build login request properties
			LoginRequest loginRequest = new LoginRequest();
            if (_userName.Length < 1)
            {
                // to handle cases where the user just clicks Connect without entering a username
                _userName = "******" + rnd.Next(10000);
            }

            GameObject sharedES = GameObject.Find("SharedES");
            SharedElectroServer gm = (SharedElectroServer)sharedES.GetComponent<SharedElectroServer>();
            gm.es = _es;
            gm.userName = _userName;
            waitingMessage = "Sending login request";
            Debug.Log("Sending login request");

            loginRequest.UserName = _userName;
			loginRequest.Password = "******";
			
			// Send to ES for request obj
			_es.Engine.Send(loginRequest);
			
		} else {
			
			Debug.Log("Connection Failed");
            waitingMessage = "Connection Failed";
			
		}
	
	}
    internal void OnConnectionResponse(ConnectionResponse response)
    {
        Debug.Log("OnConnection Response : " + response.ResponseStatus);
        mNearbyStatus = "OnConnectionResponse: " + response.ResponseStatus;
        switch (response.ResponseStatus)
        {
            case ConnectionResponse.Status.Accepted:
                mEndpoints[response.RemoteEndpointId].State = EndpointState.CONNECTED;
                break;
            case ConnectionResponse.Status.Rejected:
                mEndpoints[response.RemoteEndpointId].State = EndpointState.REJECTED;
                break;
            case ConnectionResponse.Status.NetworkError:
                mEndpoints[response.RemoteEndpointId].State = EndpointState.ERROR;

                break;
        }
    }
 internal void OnConnectionResponse(ConnectionResponse response)
 {
     Debug.Log("OnConnection Response : " + response.ResponseStatus);
     mNearbyStatus = "OnConnectionResponse: " + response.ResponseStatus;
     switch (response.ResponseStatus)
     {
         case ConnectionResponse.Status.Accepted:
             mEndpoints[response.RemoteEndpointId].State = EndpointState.CONNECTED;
             break;
         case ConnectionResponse.Status.Rejected:
             mEndpoints[response.RemoteEndpointId].State = EndpointState.REJECTED;
             break;
         case ConnectionResponse.Status.ErrorAlreadyConnected:
             // it is an error, but we can treat it like connected.
             mEndpoints[response.RemoteEndpointId].State = EndpointState.CONNECTED;
             break;
         case ConnectionResponse.Status.ErrorEndpointNotConnected:
             mEndpoints[response.RemoteEndpointId].State = EndpointState.ERROR;
             break;
         case ConnectionResponse.Status.ErrorInternal:
             mEndpoints[response.RemoteEndpointId].State = EndpointState.ERROR;
             break;
         case ConnectionResponse.Status.ErrorNetworkNotConnected:
             mEndpoints[response.RemoteEndpointId].State = EndpointState.ERROR;
             break;
         default:
             Debug.LogError("Unknown or unsupported status: " + response.ResponseStatus);
             if (mEndpoints.ContainsKey(response.RemoteEndpointId)) {
                 mEndpoints[response.RemoteEndpointId].State = EndpointState.ERROR;
             }
             break;
     }
 }