示例#1
0
        private IObservable <string> ConnectToServer()
        {
            return(Observable.Create <string>(async o =>
            {
                try
                {
                    OnConnecting?.Invoke(this, new EventArgs());
                    await _wsConnection.ConnectAsync(WebSocketUrl, CancellationToken.None).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    string error = ex.Message;

                    WebSocketException wex = FetchSocketException(ex);
                    if (wex == null && ex.InnerException != null)
                    {
                        error = $"{ex.InnerException.Message}";
                    }
                    else if (wex != null)
                    {
                        error = $"{wex.Message}";
                    }

                    OnConnectFail?.Invoke(this, new EventArgs());

                    Thread.Sleep(RetryInterval);

                    o.OnError(ex);
                }

                return Disposable.Empty;
            }));
        }
示例#2
0
 public void Connect()
 {
     ConnectionFailed = false;
     Task.Run(() => {
         try
         {
             if (Ip == null)
             {
                 return;
             }
             OnConnecting?.Invoke(this, null);
             client?.Dispose();
             client = new TcpClient(Ip.ToString(), Port)
             {
                 NoDelay = true
             };
             nwStream = client.GetStream();
             if (TurnOnWhenConnected)
             {
                 Turn(true);
             }
             OnConnect?.Invoke(this, null);
         }
         catch (Exception)
         {
             ConnectionFailed = true;
             OnConnectFail?.Invoke(this, null);
         }
     });
 }
示例#3
0
 public static void InitializeConnection()
 {
     OnConnecting?.Invoke(null, new ConnectingToServerEventArgs()
     {
         Address = StaticData.ClientInstance.Url.Host, Port = StaticData.ClientInstance.Url.Port
     });
     StaticData.LoggerInstance.Log(Utils.LogEntryType.Info, "Connecting to \"" + StaticData.ClientInstance.Url + "\"...");
     StaticData.ClientInstance.Connect();
 }
示例#4
0
        /// <summary>
        /// Creates a new <see cref="NetClient"/> instance.
        /// </summary>
        /// <param name="checkInterval">Interval in milliseconds between keepalive transmissions</param>
        /// <param name="timeout">Duration in milliseconds after which the connection will be terminated if no response is received</param>
        public NetClient(int checkInterval = 5000, int timeout = 30000)
        {
            // Set up the client
            clientNetManager = new NetManager(listener, "Phinix")
            {
                PingInterval      = checkInterval,
                DisconnectTimeout = timeout
            };

            // Forward events
            listener.PeerConnectedEvent    += (peer) => { OnConnecting?.Invoke(this, EventArgs.Empty); };
            listener.PeerDisconnectedEvent += (peer, info) => { OnDisconnect?.Invoke(this, EventArgs.Empty); };
        }
示例#5
0
        private async Task AwaitConnectingState()
        {
            if (ConnectingEventHandlerStatus == null)
            {
                //ConnectingEventHandlerStatus = Task.CompletedTask.WaitUntil(
                //    () => Connection.State == HubConnectionState.Connecting ||
                //          Connection.State == HubConnectionState.Reconnecting, EventCheckFrequency,
                //    shouldLogInLoop: logInEventAwaiting, logMessage: () => $"Waiting for connection state to become {HubConnectionState.Connecting}" +
                //                                       $" or {HubConnectionState.Reconnecting}. Current state is: {Connection.State}");
                await ConnectingEventHandlerStatus;
                ConnectingEventHandlerStatus = null;

                //Logging.Logging.Log(LogType.Event, $"{HubNameWithDefault}: Connection State changed to: {Connection.State}");
                OnConnecting?.Invoke(Connection, HubNameWithDefault, EventArgs.Empty);

                AwaitConnectedState();
                AwaitDisconnectedState();
            }
        }
示例#6
0
        /// <summary>
        /// Attempts to connect to the given endpoint. This will close an existing connection.
        /// </summary>
        /// <param name="endpoint">Endpoint to connect to</param>
        public void Connect(IPEndPoint endpoint)
        {
            // Close the active connection before we make a new one.
            Disconnect();

            // Try to connect
            clientNetManager.Start();
            serverPeer = clientNetManager.Connect(endpoint.Address.ToString(), endpoint.Port);

            // Start a polling thread to check for incoming packets
            pollThread = new Thread(() =>
            {
                while (true)
                {
                    clientNetManager.PollEvents();
                    Thread.Sleep(10);
                }
            });
            pollThread.Start();

            // Raise the connection event
            OnConnecting?.Invoke(this, EventArgs.Empty);
        }
 private void MREApp_OnConnecting()
 {
     GD.Print("Connecting");
     OnConnecting?.Invoke(this);
 }
示例#8
0
 private void MREApp_OnConnecting()
 {
     Debug.Log("Connecting");
     OnConnecting?.Invoke(this);
 }
		private void Invoke_OnConnecting()
		{
			_eventQueue.Add(() => OnConnecting?.Invoke());
		}
 private void Conn_OnConnecting()
 {
     OnConnecting?.Invoke();
 }
示例#11
0
        public async Task ConnectAsync()
        {
            if (SelectedWiFiNetwork == null)
            {
                OnError?.Invoke(this, new ArgumentException("Network not selected"));
                return;
            }
            WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual;

            if (SelectedWiFiNetwork.ConnectAutomatically)
            {
                reconnectionKind = WiFiReconnectionKind.Automatic;
            }
            Task <WiFiConnectionResult> didConnect = null;
            WiFiConnectionResult        result     = null;

            if (SelectedWiFiNetwork.IsEapAvailable)
            {
                if (SelectedWiFiNetwork.UsePassword)
                {
                    var credential = new PasswordCredential();
                    if (!String.IsNullOrEmpty(SelectedWiFiNetwork.Domain))
                    {
                        credential.Resource = SelectedWiFiNetwork.Domain;
                    }
                    credential.UserName = SelectedWiFiNetwork.UserName ?? "";
                    credential.Password = SelectedWiFiNetwork.Password ?? "";

                    didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind, credential).AsTask();
                }
                else
                {
                    didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind).AsTask();
                }
            }
            else if (SelectedWiFiNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 &&
                     SelectedWiFiNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
            {
                didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind).AsTask();
            }
            else
            {
                // Only the password potion of the credential need to be supplied
                if (String.IsNullOrEmpty(SelectedWiFiNetwork.Password))
                {
                    didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind).AsTask();
                }
                else
                {
                    var credential = new PasswordCredential();
                    credential.Password = SelectedWiFiNetwork.Password ?? "";

                    didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind, credential).AsTask();
                }
            }

            OnConnecting?.Invoke(this, EventArgs.Empty);

            if (didConnect != null)
            {
                result = await didConnect;
            }

            if (result != null && result.ConnectionStatus == WiFiConnectionStatus.Success)
            {
                WiFiNetworks.Remove(SelectedWiFiNetwork);
                WiFiNetworks.Insert(0, SelectedWiFiNetwork);
                OnSelect?.Invoke(this, EventArgs.Empty);
                OnConnected?.Invoke(this, EventArgs.Empty);
            }
            else
            {
                OnError?.Invoke(this, new Exception("Could not connect to network"));
                OnDisconnected?.Invoke(this, EventArgs.Empty);
            }

            // Since a connection attempt was made, update the connectivity level displayed for each
            foreach (var network in WiFiNetworks)
            {
                await network.UpdateConnectivityLevel();
            }
        }
示例#12
0
        /// <summary>
        /// Connects to the first of the given endpoints to establish a connection.
        /// </summary>
        /// <param name="endpoints">Endpoints to try connect to</param>
        public void Connect(IEnumerable <IPEndPoint> endpoints)
        {
            // Close the active connection before we make a new one
            Disconnect();

            // Start the client
            clientNetManager.Start();

            // Iterate over the endpoints we've been given and try to connect to them
            foreach (IPEndPoint endpoint in endpoints)
            {
                probePeers.Add(clientNetManager.Connect(endpoint.Address.ToString(), endpoint.Port));
            }

            // Start a polling thread to check for incoming packets
            pollThread = new Thread(() =>
            {
                while (true)
                {
                    clientNetManager.PollEvents();
                    Thread.Sleep(10);
                }
            });
            pollThread.Start();

            // Invoke the OnConnecting event early before we shard off into another thread
            OnConnecting?.Invoke(this, EventArgs.Empty);

            // Connect to each peer asynchronously and keep the one that works
            probeThread = new Thread(() =>
            {
                // Spin until one of the peers connects
                while (true)
                {
                    // Make sure there is at least one non-null peer
                    if (probePeers.All(peer => peer == null))
                    {
                        break;
                    }
                    // ...and that none are connected
                    if (probePeers.Where(peer => peer != null).Any(peer => peer.ConnectionState == ConnectionState.Connected))
                    {
                        break;
                    }
                    // ...and that not all of them are disconnected
                    if (probePeers.Where(peer => peer != null).All(peer => peer.ConnectionState == ConnectionState.Disconnected))
                    {
                        break;
                    }

                    Thread.Sleep(10);
                }

                NetPeer connectedPeer;
                try
                {
                    // Apply the connected one
                    connectedPeer = probePeers.First(peer => peer.ConnectionState == ConnectionState.Connected);
                    serverPeer    = connectedPeer;
                }
                catch (InvalidOperationException)
                {
                    // No connected peers available, disconnect
                    connectedPeer = null;
                    Disconnect();
                }

                // Cancel the remainder
                probePeers.RemoveAll(peer => peer == null || peer.Equals(connectedPeer));
                clearProbePeers();
            });
            probeThread.Start();
        }
示例#13
0
 public void Connect()
 {
     OnConnecting?.Invoke();
     Socket.BeginConnect(Configuration.EP, beginConnect, new Buffers.HTTP.Read(new byte[4096]));
 }
示例#14
0
 public void RaiseOnConnecting(KL2_Server server) =>
 OnConnecting?.Invoke(server);
示例#15
0
文件: Server.cs 项目: davuxcom/IRCLib
        public void Connect()
        {
            new Thread(delegate()
            {
                try
                {
                    try
                    {
                        if (Reader != null)
                        {
                            Reader.Abort();
                        }
                        if (Connection != null)
                        {
                            Connection.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine("IRC/Server/Disconnect: " + ex);
                    }
                    new Thread(delegate()
                    {
                        if (OnConnecting != null)
                        {
                            OnConnecting.Invoke(this);
                        }
                    }).Start();
                    autoJoined = false;
                    Connection = new TcpClient();
                    Connection.Connect(HostName, Port);
                    _Network = HostName;
                    Reader   = new Thread(ReaderStart);
                    Reader.Start();

                    Writer           = new StreamWriter(Connection.GetStream());
                    Writer.AutoFlush = true;

                    Event.Invoke(this, Event.ServerEventType.ConnectedNoLogin, null);

                    if (!string.IsNullOrEmpty(Password))
                    {
                        Send("PASS " + Password);
                    }
                    Send("NICK " + Profile.Nick);
                    Nick = Profile.Nick;
                    Send("USER " + Profile.User + " hostname servername :" + Profile.RealName);
                    Event.Invoke(this, Event.ServerEventType.ConnectedLoginSent, null);
                    // OPER would happen here, on the event.
                }
                catch (Exception ex)
                {
                    new Thread(delegate()
                    {
                        if (OnError != null)
                        {
                            OnError.Invoke(this, ex);
                        }
                    }).Start();
                }
            }).Start();
        }