Ejemplo n.º 1
0
        /// <summary>
        /// connect to exchange
        /// установить соединение с биржей
        /// </summary>
        public void Connect()
        {
            if (string.IsNullOrWhiteSpace(_apiKeyPublic) ||
                string.IsNullOrWhiteSpace(_apiKeySecret) ||
                string.IsNullOrWhiteSpace(_clientId))
            {
                return;
            }
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            // check server availability for HTTP communication with it / проверяем доступность сервера для HTTP общения с ним
            Uri uri = new Uri("https://www.bitstamp.net");

            try
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(uri);

                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            }
            catch
            {
                LogMessageEvent("Сервер не доступен. Отсутствуюет интернет. ", LogMessageType.Error);
                return;
            }

            IsConnected = true;

            if (Connected != null)
            {
                Connected();
            }

            // start stream data through WebSocket / запускаем потоковые данные через WebSocket

            _ws = new ClientWebSocket();

            Uri wsUri = new Uri("wss://ws.bitstamp.net");

            _ws.ConnectAsync(wsUri, CancellationToken.None).Wait();

            if (_ws.State == WebSocketState.Open)
            {
                if (Connected != null)
                {
                    Connected.Invoke();
                }
                IsConnected = true;
            }

            Thread worker = new Thread(GetRes);

            worker.CurrentCulture = new CultureInfo("ru-RU");
            worker.IsBackground   = true;
            worker.Start(_ws);

            Thread converter = new Thread(Converter);

            converter.CurrentCulture = new CultureInfo("ru-RU");
            converter.IsBackground   = true;
            converter.Start();
        }
Ejemplo n.º 2
0
 protected virtual void OnConnected()
 {
     if (Connected != null)
     {
         Connected.Invoke();
     }
 }
Ejemplo n.º 3
0
 private void ConnectCompleted(object sender, SocketAsyncEventArgs args)
 {
     if (args.SocketError == SocketError.Success)
     {
         if (Connected != null)
         {
             Connected.Invoke(this, _client);
         }
         try
         {
             SocketAsyncEventArgs rArgs = new SocketAsyncEventArgs();
             rArgs.Completed += ReceiveCompleted;
             rArgs.SetBuffer(new byte[8912], 0, 8912);
             rArgs.UserToken = new MemoryStream();
             if (!_client.ReceiveAsync(rArgs))
             {
                 ReceiveCompleted(this, args);
             }
         }
         catch (NotSupportedException nse) { throw nse; }
         catch (ObjectDisposedException oe) { throw oe; }
         catch (SocketException se) { throw se; }
         catch (Exception e) { throw e; }
     }
     else
     {
         Stop();
     }
 }
Ejemplo n.º 4
0
 protected void FireConnectedEvent()
 {
     if (Connected != null)
     {
         Connected.Invoke();
     }
 }
Ejemplo n.º 5
0
        public static int SuperB_Login(string ip, int port,
                                       string sUserName, string sPassword,
                                       ref SuperB_PlateInfo lpDeviceInfo)
        {
            int  userIndex = -1;
            BSDK tmp       = new BSDK();

            tmp.Initial(ip, port, new User()
            {
                username = sUserName.ToCharArray(),
                password = sPassword.ToCharArray(),
                Eright   = EnumRightMode.LEVEL2,
            });

            if (_sdkList.TryAdd(_sdkList.Count, tmp))
            {
                userIndex = _sdkList.Count - 1;
                tmp.SetCallBackFun(
                    (cmd, objs) => DataCallback(userIndex, cmd, objs),
                    (cmd, objs) =>
                {
                    if (cmd == Sdk_StatusEvent.Closed)
                    {
                        Disconnected.Invoke(userIndex);
                    }
                    else
                    {
                        Connected.Invoke(userIndex);
                    }
                });
                tmp.StartWork();
            }

            return(userIndex);
        }
        public void ConnectAsync()
        {
            ThreadPool.QueueUserWorkItem(payload =>
            {
                try
                {
                    byte ret = _client.Connect(_clientId, _username, _password, _cleanSession, 30);
                    if (ret == 0)
                    {
                        if (Connected != null)
                        {
                            _dispatcher.Post(() => Connected.Invoke(this, _client.SessionPresent));
                        }
                    }
                    else
                    {
                        switch (ret)
                        {
                        case 5:
                            OnDisconnected(false, new FizzMqttAuthException());
                            break;

                        default:
                            OnDisconnected(false, new FizzMqttConnectException(ret, "connect_failed"));
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    OnDisconnected(false, ex);
                }
            });
        }
Ejemplo n.º 7
0
        private void SetStatus(EConnectionStatus status)
        {
            switch (status)
            {
            case EConnectionStatus.Connecting:
                if (Status != EConnectionStatus.Connecting)
                {
                    Status = EConnectionStatus.Connecting;
                }
                break;

            case EConnectionStatus.Connected:
                if (Status != EConnectionStatus.Connected)
                {
                    Status = EConnectionStatus.Connected;
                    CoroutineHelper.StartCoroutine(_peer.SendDelayedMessages());
                    if (Connected != null)
                    {
                        Connected.Invoke();
                    }
                }
                break;

            case EConnectionStatus.Disconnected:
                if (Status != EConnectionStatus.Disconnected)
                {
                    Status = EConnectionStatus.Disconnected;
                    if (Disconnected != null)
                    {
                        Disconnected.Invoke();
                    }
                }
                break;
            }
        }
Ejemplo n.º 8
0
 private static void Client_Connected(object sender, EventArgs e)
 {
     if (Connected != null)
     {
         Connected.Invoke(sender, e);
     }
 }
Ejemplo n.º 9
0
        /// <summary>
        /// установить соединение с сервером
        /// </summary>
        public void Connect()
        {
            Uri uri = new Uri(_serverAdress);

            _ws.ConnectAsync(uri, CancellationToken.None).Wait();

            if (_ws.State == WebSocketState.Open)
            {
                if (Connected != null)
                {
                    Connected.Invoke();
                }
                IsConnected = true;
            }

            Thread worker = new Thread(GetRes);

            worker.CurrentCulture = new CultureInfo("ru-RU");
            worker.IsBackground   = true;
            worker.Start(_ws);

            Thread converter = new Thread(Converter);

            converter.CurrentCulture = new CultureInfo("ru-RU");
            converter.IsBackground   = true;
            converter.Start();

            Thread wspinger = new Thread(_pinger);

            wspinger.CurrentCulture = new CultureInfo("ru-RU");
            wspinger.IsBackground   = true;
            wspinger.Start();

            Auth();
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Fires when the XMPP is connected
 /// </summary>
 /// <returns></returns>
 public async Task OnConnectAsync()
 {
     if (Connected != null)
     {
         await Connected.Invoke();
     }
 }
Ejemplo n.º 11
0
 private void OnConnected(object sender, MqttClientConnectedEventArgs args)
 {
     if (Connected != null)
     {
         _dispatcher.Post(() => Connected.Invoke(_id, sender, args));
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Performs the initial Slack integration.
        /// </summary>
        public void StartIntegration()
        {
            client = new SlackSocketClient(Token);

            client.Connect((loginResponse) =>
            {
                Connected.Invoke(this, null);
                client.OnMessageReceived += (obj) =>
                {
                    SlackMessageEventArgs e = new SlackMessageEventArgs
                    {
                        Text   = obj.text,
                        Member = new SlackMember(GetUserByName(obj.user))
                    };
                    e.Channel = GetChannelByName(obj.channel) == null ? new SlackChannel(e.Member.Name, obj.channel) : new SlackChannel(GetChannelByName(obj.channel));
                    if (e.Text.Contains($"<@{client.MySelf.id}>"))
                    {
                        MentionReceived?.Invoke(this, e);
                    }
                    else
                    {
                        MessageReceived?.Invoke(this, e);
                    }
                };
            },
                           () =>
            {
                //socket connected
            });
        }
Ejemplo n.º 13
0
 private void OnServerConnection()
 {
     if (Connected != null)
     {
         Connected.Invoke(_socketClient);
     }
 }
Ejemplo n.º 14
0
 protected virtual void OnConnect(INetworkConnection connection)
 {
     if (Connected != null)
     {
         Connected.Invoke(connection);
     }
 }
        private void HandleConnect(int connectionId, byte error)
        {
            if (_connectionId != connectionId)
            {
                return;
            }

            _isConnectionPending = false;

            IsConnecting = false;
            IsConnected  = true;

            Status = ConnectionStatus.Connected;

            if (_serverPeer != null)
            {
                _serverPeer.MessageReceived -= HandleMessage;
            }

            _serverPeer = new PeerUnet(connectionId, _socketId);
            Peer        = _serverPeer;
            _serverPeer.SetIsConnected(true);
            _serverPeer.MessageReceived += HandleMessage;

            if (Connected != null)
            {
                Connected.Invoke();
            }
        }
Ejemplo n.º 16
0
        private void OnConnect(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                var client = (TcpClient)ar.AsyncState;

                // Complete the connection.
                client.EndConnect(ar);

                _tcpStream = _tcpClient.GetStream();

                if (Connected != null)
                {
                    Connected.Invoke(this);
                }

                _reader.StartReceiving(_tcpStream, Process);
            }
            catch (Exception ex)
            {
                if (ErrorOccured != null)
                {
                    ErrorOccured.Invoke(this, ex);
                }
            }
        }
Ejemplo n.º 17
0
 public void OnConnected()
 {
     if (Connected != null)
     {
         Connected.Invoke(this);
     }
 }
Ejemplo n.º 18
0
 public void Start()
 {
     foreach (Transport t in transports)
     {
         t.Connected.AddListener(c => Connected.Invoke(c));
         t.Started.AddListener(() => Started.Invoke());
     }
 }
Ejemplo n.º 19
0
 private void OnConnected()
 {
     if (Connected != null)
     {
         Connected.Invoke(this, new EventArgs());
     }
     BeginReceiving();
 }
Ejemplo n.º 20
0
        public new void Connect(bool useDotNetWebsocket)
        {
            Console.WriteLine("Faking Discord session.....");

            Thread.Sleep(1000);


            Connected.Invoke(this, new DiscordConnectEventArgs());
        }
Ejemplo n.º 21
0
    //---------------------------------------------------------------------
    void _raiseConnected()
    {
        mQueIPAddress.Clear();

        if (Connected != null)
        {
            Connected.Invoke(null, EventArgs.Empty);
        }
    }
Ejemplo n.º 22
0
 public IDatabase Connect(string connection)
 {
     _sqLiteDatabase = _sqLiteDatabaseBuilder.Build(connection);
     if (Connected != null)
     {
         Connected.Invoke(this, EventArgs.Empty);
     }
     return(this);
 }
Ejemplo n.º 23
0
        private async Task OnConnected(object source, ConnectedEventArgs args)
        {
            if (Connected == null)
            {
                return;
            }

            await Connected.Invoke(source, args);
        }
Ejemplo n.º 24
0
        private bool ConnectToClient()
        {
            int delay = 0;

            try
            {
                // Connect to TcpClient
                if (client == null || !client.Connected)
                {
                    // Create a new TcpClient
                    client = new TcpClient(_serverHostname, _port);
                    client.ReceiveTimeout = Timeout;
                    client.SendTimeout    = Timeout;

                    // Get Stream
                    if (_useSSL)
                    {
                        // Create new SSL Stream from client's NetworkStream
                        var sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                        sslStream.AuthenticateAsClient(_serverHostname);
                        PrintCertificateInfo(sslStream);

                        stream = Stream.Synchronized(sslStream);
                    }
                    else
                    {
                        stream = Stream.Synchronized(client.GetStream());
                    }

                    streamWriter = new StreamWriter(stream);
                    streamReader = new StreamReader(stream);

                    log.Info("Connection Established with " + ServerHostname + ":" + _port);
                    Connected.Invoke(this, new EventArgs());
                    connected = true;
                }

                return(true);
            }
            catch (Exception ex)
            {
                if (client != null)
                {
                    client.Close();
                }
                log.Warn("Error Connecting to " + ServerHostname + ":" + _port + ". Retrying in " + delay + "ms..");
                log.Trace(ex);
            }

            if (!connected)
            {
                Disconnected.Invoke(this, new EventArgs());
            }

            return(false);
        }
Ejemplo n.º 25
0
        static void Socket_Connected(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            IsConnected = true;
            if (Connected != null)
            {
                Connected.Invoke(socket, new EventArgs());
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// When the wrapper / bot has connected to an API
        /// </summary>
        /// <param name="wrapper">The wrapper that has connected to the API</param>
        internal Task OnWrapperConnectedAsync(ApiWrapper.ApiWrapper wrapper)
        {
            LoggerFactory
            .CreateLogger(GetType().FullName)
            .LogTrace($"{nameof(Connected)}: Wrapper: {wrapper.Name}");

            return(Connected != null
                ? Connected.Invoke(wrapper)
                : Task.CompletedTask);
        }
Ejemplo n.º 27
0
        public FedNetClient(ConnectorData MQTTConnectorData, IFedNetLogger newlogSystem = null)
        {
            _logSystem = newlogSystem;
            if (_logSystem == null)
            {
                _logSystem = new DefaultLogger();
            }

            _MQTTHostAndPort = MQTTConnectorData.getHasSE();

            _ClientConfiguration = new MqttClientOptionsBuilder();
            _ClientConfiguration.WithClientId(String.Format("{0}-{1}_{2}", MQTTConnectorData.Username, DateTime.Now.ToString("ffffmmHHss"), FedNetWorker.getRandomString(10)));
            if (MQTTConnectorData.useCreditential)
            {
                _ClientConfiguration.WithCredentials(MQTTConnectorData.Username, MQTTConnectorData.Password);
            }
            _ClientConfiguration.WithTcpServer(MQTTConnectorData.Host, MQTTConnectorData.Port);

            _theGameClient = new MqttFactory().CreateMqttClient();
            _theGameClient.UseDisconnectedHandler(e => {
                _logSystem.Info("Disconnected (reason : " + (e.AuthenticateResult != null ? e.AuthenticateResult.ResultCode.ToString() : "unknow") + ")");
                if (Disconnected != null)
                {
                    Disconnected.Invoke(this, e);
                }
                if (reconnectOnDisco)
                {
                    Task.Delay(1000).Wait();
                    Connect();
                }
            });
            _theGameClient.UseConnectedHandler(e => {
                _logSystem.Info("Connected !!");
                _theGameClient.SubscribeAsync(FedNetConstante.SERVER_TO_CLIENT + FedNetConstante.DEFAULT_TOPIC_SEPARATOR + ClientId + FedNetConstante.DEFAULT_TOPIC_SEPARATOR + FedNetConstante.DEFAULT_TOPIC_JOKER, (MqttQualityOfServiceLevel)FedNetConstante.PRIORITY_SERVER_TO_CLIENT);
                _theGameClient.SubscribeAsync(FedNetConstante.SERVER_BROADCAST + FedNetConstante.DEFAULT_TOPIC_SEPARATOR + FedNetConstante.DEFAULT_TOPIC_JOKER, (MqttQualityOfServiceLevel)FedNetConstante.PRIORITY_SERVER_BROADCAST);
                if (Connected != null)
                {
                    Connected.Invoke(this, e);
                }
            });
            _theGameClient.UseApplicationMessageReceivedHandler(e => {
                if (e.ClientId == "" || e.ClientId == " " || e.ClientId == null)
                {
                    return;
                }
                if (MessageReceived != null)
                {
                    MessageReceived.Invoke(this, Message.getMessage(e.ApplicationMessage));
                }
            });

            reconnectOnDisco = true;

            _logSystem.Info("Client initialized !");
        }
Ejemplo n.º 28
0
 private void CallbackConnect(IAsyncResult ar)
 {
     _socket.EndConnect(ar);
     _connected = true;
     if (Connected != null)
     {
         Connected.Invoke(this, EventArgs.Empty);
     }
     byte[] buffer = new byte[_socket.SendBufferSize];
     _socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(CallbackReceive), buffer);
 }
Ejemplo n.º 29
0
 /// <summary>
 /// This is called when all of the console variables have been received from
 /// the Vector.  It may post the connected event to the application
 /// </summary>
 void ReceivedVars()
 {
     hasVars = true;
     if (connected8888 && connected8889 && hasVars)
     {
         if (null != Connected)
         {
             Console.WriteLine("Server connected");
             Connected.Invoke(this, EventArgs.Empty);
         }
     }
 }
Ejemplo n.º 30
0
 private void Bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     if (e.Cancelled == false && e.Error == null)
     {
         currentSeq        = 0;
         netStream         = tcp.GetStream();
         heartbeatSendable = 1;
         packetRecvThread  = new Thread(new ThreadStart(packetRecvThreadStart));
         packetRecvThread.Start();
         log("OK: Connected");
         Connected.Invoke(true);
     }
 }