Пример #1
0
 /// <summary>
 /// On connection established event
 /// </summary>
 /// <param name="end">client address</param>
 protected virtual void OnConnectionEstablished(IPEndPoint end)
 {
     try
     {
         ConnectionEstablished?.Invoke(this, new ConnectionEventArgs()
         {
             Address        = end.ToString(),
             ConnectionTime = DateTime.Now
         });
     }
     catch
     {
         throw;
     }
 }
Пример #2
0
 /// <summary>
 /// (re)establish the connection to the specified ip
 /// </summary>
 /// <returns></returns>
 public void Connect()
 {
     Task.Run(() => {
         Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");
         Debug.WriteLine($"Trying to connect to {ip}");
         client = new TcpClient();
         try {
             client.Connect(ip, 8888);
             Debug.WriteLine("Connection successfull");
             stream = client.GetStream();
             ConnectionEstablished?.Invoke(this, EventArgs.Empty);
         } catch (SocketException e) {
             ConnectFailed?.Invoke(this, EventArgs.Empty);
             Debug.WriteLine($"Couldn't connect because of {e}");
         }
     });
 }
        public SerialPortRUSConnectionInterface(IInterface port)
        {
            _port = port;

            _port.ConnectionEstablished += _base_ConnectionEstablished;
            _port.ConnectionClosed      += _base_ConnectionClosed;

            void _base_ConnectionClosed(object sender, EventArgs e)
            {
                ConnectionClosed?.Invoke(sender, e);
            }

            void _base_ConnectionEstablished(object sender, EventArgs e)
            {
                ConnectionEstablished?.Invoke(sender, e);
            }
        }
Пример #4
0
        public void Open(string portName, int baudRate)
        {
            if (IsOpen)
            {
                Close();
            }

            var status = getDevice(out _openedDevice);

            status = status == FT_STATUS.FT_OK ? _ftdi.OpenByLocation(_openedDevice.LocId) : status;
            status = status == FT_STATUS.FT_OK ? _ftdi.SetBaudRate(baudRate.ToUInt32()) : status;
            status = status == FT_STATUS.FT_OK ? _ftdi.SetDataCharacteristics(8, 0, 0) : status;
            status = status == FT_STATUS.FT_OK ? _ftdi.SetFlowControl(0x0000, 0x00, 0x00) : status;
            status = status == FT_STATUS.FT_OK ? _ftdi.SetLatency(1) : status;
            status = status == FT_STATUS.FT_OK ? _ftdi.SetUSBParameters(32768, 0) : status;
            status = status == FT_STATUS.FT_OK ? _ftdi.SetTimeouts(1, 1) : status;

            if (status == FT_STATUS.FT_OK)
            {
                PortName = portName;

                ConnectionEstablished?.Invoke(this);
            }
            else
            {
                Logger.LogError($"Не удалось открыть порт {portName}", $"-MSG, статус: {status}");

                _openedDevice = null;
                Close();
            }

            FT_STATUS getDevice(out FT_DEVICE_INFO_NODE device)
            {
                var index = portName
                            .SkipWhile(char.IsLetter)
                            .Aggregate()
                            .ParseToUInt32Invariant();

                device = getAllDevices().ElementAtOrDefault((int)index);

                return(device == null ? FT_STATUS.FT_DEVICE_NOT_FOUND : FT_STATUS.FT_OK);
            }
        }
Пример #5
0
        private void OnStateChangedEvent(UnityMCPeerID arg1, UnityMCSessionState arg2)
        {
            // todo: handle multi-user
            Debug.Log("State: " + arg2.ToString() + " with user: "******"Unexpected state: " + arg2);
                break;
            }
        }
Пример #6
0
 public bool Connect()
 {
     CloseConnection();
     TCPClient = new TcpClient();
     try
     {
         TCPClient.Connect(IPAddress, Port);
         DataStream = TCPClient.GetStream();
         Log($"connect successully!!");
         Init();
         Log($"invoking ConnectionEstablished");
         ConnectionEstablished?.Invoke();
         Log($"invoking ConnectionEstablished, done");
         return(true);
     }
     catch (Exception e)
     {
         Log($"exception thrown when connecting {e.Message}");
         TCPClient.Dispose();
         return(false);
     }
 }
Пример #7
0
        /// <summary>
        /// Accept new connections.
        /// </summary>
        /// <param name="asyncResult"></param>
        private void AcceptCallback(IAsyncResult asyncResult)
        {
            //Stops accepting new connections when listenSocket is shutdown
            if (State == ServerState.Down)
            {
                return;
            }

            //Accept the new connection
            Socket acceptedSocket = listenSocket.EndAccept(asyncResult);
            byte   clientId       = AddClient(acceptedSocket);

            //Send the id to the client
            acceptedSocket.Send(Commands.SetPlayerId(clientId));

            //Start receiving data from the client
            ConnectionEstablished?.Invoke();
            BeginReceiving(acceptedSocket);

            //Start accepting the next connection
            BeginAccepting();
        }
Пример #8
0
        public void Start()
        {
            if (socket != null && ClientOptions != null)
            {
                if (!Running)
                {
                    Running = true;
                    ConnectionEstablished?.Invoke(this);
                    DOSWatch  = Stopwatch.StartNew();
                    pingWatch = Stopwatch.StartNew();

                    BeginReceive();
                }
                else
                {
                    throw new InvalidOperationException("Client is already running");
                }
            }
            else
            {
                throw new InvalidOperationException("Socket or SocketOptions can't be null");
            }
        }
Пример #9
0
 private void SendReadyToServer()
 {
     byte[] data = BitConverter.GetBytes((short)LocalConnectionID);
     Send(ConnectionID, ReliableChannel, ClientReadyMsg, data);
     ConnectionEstablished?.Invoke(m_Connections[LocalConnectionID]);
 }
Пример #10
0
 protected virtual void OnConnectionEstablished(WampSessionCreatedEventArgs e)
 {
     ConnectionEstablished?.Invoke(this, e);
 }
 private void OnConnectionEstablished()
 {
     ConnectionEstablished?.Invoke();
 }
Пример #12
0
 protected void OnConnectionEstablished(ConnectionEventArgs e)
 {
     ConnectionEstablished?.Invoke(this, e);
 }
Пример #13
0
 public virtual void OnConnectionEstablished(ConnectionEstablishedArgs e)
 {
     ConnectionEstablished?.Invoke(this, e);
 }
Пример #14
0
 private void OnConnectionEstablished()
 {
     ConnectionEstablished?.Invoke(this, new EventArgs());
 }
Пример #15
0
        /// <summary>
        ///   Called when a remote peer is connecting to the local peer.
        /// </summary>
        /// <param name="stream">
        ///   The stream to the remote peer.
        /// </param>
        /// <param name="local">
        ///   The local peer's address.
        /// </param>
        /// <param name="remote">
        ///   The remote peer's address.
        /// </param>
        /// <remarks>
        ///   Establishes the protocols of the connection.  Any exception is simply
        ///   logged as warning.
        /// </remarks>
        async void OnRemoteConnect(Stream stream, MultiAddress local, MultiAddress remote)
        {
            // If the remote is already trying to establish a connection, then we
            // can just refuse this one.
            if (!pendingRemoteConnections.TryAdd(remote, null))
            {
                log.Debug($"Duplicate remote connection from {remote}");
                stream.Dispose();
                return;
            }

            try
            {
                log.Debug($"{LocalPeer.Id} got remote connection");
                log.Debug("local " + local);
                log.Debug("remote " + remote);

                // TODO: Check the policies

                var connection = new PeerConnection
                {
                    IsIncoming    = true,
                    LocalPeer     = LocalPeer,
                    LocalAddress  = local,
                    LocalPeerKey  = LocalPeerKey,
                    RemoteAddress = remote,
                    Stream        = stream
                };

                // Are we communicating to a private network?
                if (NetworkProtector != null)
                {
                    connection.Stream = await NetworkProtector.ProtectAsync(connection).ConfigureAwait(false);
                }

                // Mount the protocols.
                MountProtocols(connection);

                // Start the handshake
                // TODO: Isn't connection cancel token required.
                connection.ReadMessages(default(CancellationToken));

                // Wait for security to be established.
                await connection.SecurityEstablished.Task.ConfigureAwait(false);

                // TODO: Maybe connection.LocalPeerKey = null;

                // Wait for the handshake to complete.
                var muxer = await connection.MuxerEstablished.Task;

                // Need details on the remote peer.
                Identify1 identify = null;
                lock (protocols)
                {
                    identify = protocols.OfType <Identify1>().First();
                }
                connection.RemotePeer = await identify.GetRemotePeer(connection, default(CancellationToken)).ConfigureAwait(false);

                connection.RemotePeer    = RegisterPeer(connection.RemotePeer);
                connection.RemoteAddress = new MultiAddress($"{remote}/ipfs/{connection.RemotePeer.Id}");
                var actual = Manager.Add(connection);
                if (actual == connection)
                {
                    ConnectionEstablished?.Invoke(this, connection);
                }
            }
            catch (Exception e)
            {
                log.Warn("Remote connect failed", e);
                try
                {
                    stream.Dispose();
                }
                catch (Exception)
                {
                    // eat it.
                }
            }
            finally
            {
                pendingRemoteConnections.TryRemove(remote, out object _);
            }
        }
Пример #16
0
 public MockTCP(MockWire wire)
 {
     this.wire        = wire;
     wire.Connect    += () => ConnectionEstablished?.Invoke();
     wire.Disconnect += () => ConnectionLost?.Invoke();
 }
Пример #17
0
 //Triggers
 private void OnConnectionEstablished(Client client)
 {
     ConnectionEstablished?.Invoke(this, new ConnectionEventArgs {
         LocalEndPoint = client.Socket.LocalEndPoint, RemoteEndPoint = client.Socket.RemoteEndPoint
     });
 }
Пример #18
0
 private void OnConnectionEstablished(string comPort, int baudRate)
 {
     LastConnectedPort = comPort;
     ConnectionEstablished?.Invoke(comPort, baudRate);
 }
        private async Task TryConnect()
        {
            Action <string> ConnectionFailed     = message => ConnectionEstablished?.Invoke(this, ViewModelEventArgs.Error(message));
            Action <string> ConnectionSuccessful = message => ConnectionEstablished?.Invoke(this, ViewModelEventArgs.Information(message));

            if (string.IsNullOrWhiteSpace(address))
            {
                ConnectionFailed("Please, fill in the Address of the device.");
                return;
            }

            if (string.IsNullOrWhiteSpace(port))
            {
                port = "80";
            }

            IsConnecting = true;

            var client = Dependency.Resolve <HttpClient>();

            try
            {
                using (var body = new StringContent(Protocol.HelloMessage, Encoding.UTF8, "application/xml"))
                {
                    using (var response = await client.PostAsync("http://" + address + ":" + port + "/", body))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            var content = await response.Content.ReadAsStringAsync();

                            if (content != null)
                            {
                                if (content == Protocol.HelloReply)
                                {
                                    var connection = Dependency.Resolve <Connection>();
                                    connection.Address = address;
                                    connection.Port    = Convert.ToInt32(port);

                                    HasConnection = true;
                                    ConnectionSuccessful("Success");
                                }
                                else
                                {
                                    ConnectionFailed("Device did not respond correctly. Error may be in the network.");
                                }
                            }
                            else
                            {
                                ConnectionFailed("Device is not responding correctly.");
                            }
                        }
                        else
                        {
                            ConnectionFailed("Connection was not properly established with the device.");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ConnectionFailed("Device did not respond. Reason:\r\n" + ex.Message);
            }

            IsConnecting = false;
        }
 private void RaiseConnectionEstablished(string sessionId, string serverIdent)
 {
     ConnectionEstablished?.Invoke(this,
                                   new WampConnectionEstablishedEventArgs(sessionId, serverIdent));
 }
Пример #21
0
        /// <summary>
        ///   Establish a duplex stream between the local and remote peer.
        /// </summary>
        /// <param name="remote"></param>
        /// <param name="addrs"></param>
        /// <param name="cancel"></param>
        /// <returns></returns>
        async Task <PeerConnection> Dial(Peer remote, IEnumerable <MultiAddress> addrs, CancellationToken cancel)
        {
            log.Debug($"Dialing {remote}");

            if (remote == LocalPeer)
            {
                throw new Exception("Cannot dial self.");
            }

            // If no addresses, then ask peer routing.
            if (Router != null && addrs.Count() == 0)
            {
                var found = await Router.FindPeerAsync(remote.Id, cancel).ConfigureAwait(false);

                addrs            = found.Addresses;
                remote.Addresses = addrs;
            }

            // Get the addresses we can use to dial the remote.
            var possibleAddresses = (await Task.WhenAll(addrs.Select(a => a.ResolveAsync(cancel))).ConfigureAwait(false))
                                    .SelectMany(a => a)
                                    .Select(a => a.WithPeerId(remote.Id))
                                    .Distinct()
                                    .ToArray();

            // TODO: filter out self addresses and others.
            if (possibleAddresses.Length == 0)
            {
                throw new Exception($"{remote} has no known address.");
            }

            // Try the various addresses in parallel.  The first one to complete wins.
            PeerConnection connection = null;

            try
            {
                using (var timeout = new CancellationTokenSource(TransportConnectionTimeout))
                    using (var cts = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, cancel))
                    {
                        var attempts = possibleAddresses
                                       .Select(a => DialAsync(remote, a, cts.Token));
                        connection = await TaskHelper.WhenAnyResult(attempts, cts.Token).ConfigureAwait(false);

                        cts.Cancel(); // stop other dialing tasks.
                    }
            }
            catch (Exception e)
            {
                var attemped = string.Join(", ", possibleAddresses.Select(a => a.ToString()));
                log.Trace($"Cannot dial {attemped}");
                throw new Exception($"Cannot dial {remote}.", e);
            }

            // Do the connection handshake.
            try
            {
                MountProtocols(connection);
                IEncryptionProtocol[] security = null;
                lock (protocols)
                {
                    security = protocols.OfType <IEncryptionProtocol>().ToArray();
                }
                await connection.InitiateAsync(security, cancel).ConfigureAwait(false);

                await connection.MuxerEstablished.Task.ConfigureAwait(false);

                Identify1 identify = null;
                lock (protocols)
                {
                    identify = protocols.OfType <Identify1>().First();
                }
                await identify.GetRemotePeer(connection, cancel).ConfigureAwait(false);
            }
            catch (Exception)
            {
                connection.Dispose();
                throw;
            }

            var actual = Manager.Add(connection);

            if (actual == connection)
            {
                ConnectionEstablished?.Invoke(this, connection);
            }

            return(actual);
        }
Пример #22
0
 public void Open(string portName, int baudRate)
 {
     IsOpen = true;
     ConnectionEstablished?.Invoke(this);
 }
Пример #23
0
 void _base_ConnectionEstablished(object sender, EventArgs e)
 {
     ConnectionEstablished?.Invoke(this, e);
 }
Пример #24
0
 /// <summary>
 /// Raises the <see cref="E:ConnectionEstablished" /> event.
 /// </summary>
 /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 protected internal void OnConnectionEstablished(EventArgs e)
 {
     ConnectionEstablished?.Invoke(this, e);
 }