示例#1
0
        private void MqttClient_Disconnected(object sender, MqttClientDisconnectedEventArgs e)
        {
            ConnectEvent?.Invoke(false, e.Exception);
            if (e.Exception.InnerException is SocketException error)
            {
                switch (error.SocketErrorCode)
                {
                case SocketError.HostUnreachable:
                case SocketError.ConnectionAborted:
                case SocketError.NetworkUnreachable:
                case SocketError.ConnectionRefused:
                    Thread.Sleep(3000);
                    break;

                default:
                    Thread.Sleep(1000);
                    break;
                }
            }
            else
            {
                Thread.Sleep(125);
            }
            if (e.Exception is MqttConnectingFailedException code && code.ReturnCode == MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword)
            {
                this.userId = 0;
            }
示例#2
0
        private void MqttClient_Connected(object sender, MqttClientConnectedEventArgs e)
        {
            var topics = TopicEvent?.Invoke();

            SubscribeAsync(topics);
            ConnectEvent?.Invoke(true, null);
        }
示例#3
0
        private void OnConnectCallback(IAsyncResult ar)
        {
            Socket sock = (Socket)ar.AsyncState;
            if (sock == null) return;

            IPEndPoint ep = null;
            try
            {
                sock.EndConnect(ar);
                ep = sock.RemoteEndPoint as IPEndPoint;

                _TCP = new ATCPConnector(sock, Uid64.CreateNewSync().Data, NetHelper.READ_BUFFER_BIG);
                _TCP.DisconnectEvent += OnDisconnectEventHandler;
                _TCP.ReceiveAction += OnReceveDataHandler;
                _TCP.ReceiveComAction += OnReceiveCommandHandler;
            }
            catch (SocketException ex){
                sock.Close();
                sock = null;
                NetLogger.Log(ex);
                return;
            }

            _isActive = true;
            if (ep != null) { NetLogger.Log("Connected to " + sock.RemoteEndPoint); }
            ConnectEvent?.Invoke(this, _TCP);
        }
示例#4
0
        // отображаем данные записи
        private void SetAll()
        {
            Size = new Size(760, 50);

            Status = new Panel() { Parent = this, Location = new Point(0, 0), Size = new Size(30, 50), BackColor = Color.IndianRed };
            RoomName = new Label() { Parent = this, Location = new Point(40, 10), Size = new Size(300, 30), Font = new Font(Font.FontFamily, 18), Text = Source.Name };
            PlayersCount = new Label() { Parent = this, Location = new Point(450, 10), Size = new Size(100, 30), Font = new Font(Font.FontFamily, 18), Text = Source.Players.Count + "/" + Source.MaxCount };
            Watch = new Button() { Parent = this, Location = new Point(550, 0), Size = new Size(100, 50), Font = new Font(Font.FontFamily, 9), Text = "Наблюдать" };
            Connect = new Button() { Parent = this, Location = new Point(660, 0), Size = new Size(100, 50), Font = new Font(Font.FontFamily, 9), Text = "Подключиться" };

            SetStatusColor(Source.Status);

            // вызываем собтие, если пользователь нажал на кнопку "Подключиться"
            Connect.Click += (object sender, EventArgs e) => {
                ConnectEvent?.Invoke(this);
            };

            // вызываем собтие, если пользователь нажал на кнопку "Наблюдать"
            Watch.Click += (object sender, EventArgs e) => {
                WatchEvent?.Invoke(this);
            };

            // если статус сервера изменился - обновляем данные
            Source.ChangeRoomStatusEvent += (status) => {
                SetStatusColor(status);
            };
        }
示例#5
0
        private void Client_ClientEvent(ServiceEventArgs e)
        {
            try
            {
                if (e.Type == ServiceType.DisConnect)
                {
                    ConnectEvent?.Invoke(false);
                    switch (e.SocketError)
                    {
                    case SocketError.NotConnected:
                        Thread.Sleep(1000);
                        break;

                    default:
                        Thread.Sleep(125);
                        break;
                    }
                    Connect();
                }
            }
            catch (Exception ex)
            {
                ex.Log();
            }
        }
示例#6
0
        private void CycleMeasureCurrent(CancellationToken cancellationToken)
        {
            transport = new Transport(ip, Port);
            transport.Connect();
            commands = new SDM_Commands(transport);


            commands.SetCurrentRange(CurrentType, Range, Units);
            // commands.SetSamples(1);
            // commands.SetIntegration(10);
            // commands.CurrentFiltrOff();

            commands.InitCommand();

            StateConnect = true;
            ConnectEvent?.Invoke(this, new EventArgs());
            while (!cancellationToken.IsCancellationRequested)
            {
                // for(int i = 0; i < 4; i++)
                Current   = commands.ReadMeasValue(5) * multipler;
                Timestamp = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                UpdMeasureResult?.Invoke(this, new EventArgs());
                Thread.Sleep(300);
                //commands.InitCommand();
            }
        }
示例#7
0
        private void Client_ConnectFinished(IPEndPoint sender, SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success)
            {
                ConnectEvent?.Invoke(true);
            }
            else
            {
                ConnectEvent?.Invoke(false);
                switch (e.SocketError)
                {
                case SocketError.HostUnreachable:
                case SocketError.ConnectionAborted:
                case SocketError.NetworkUnreachable:
                case SocketError.ConnectionRefused:
                    Thread.Sleep(3000);
                    break;

                default:
                    Thread.Sleep(1000);
                    break;
                }
                Connect();
            }
        }
示例#8
0
    public void ConnectToPlayer(Element element, int playerID)
    {
        if (OnConnect != null)
        {
            OnConnect.Invoke(this);
        }

        Player player = GameManager.Instance.playList[playerID];

        player.AddElement(this);
        fixedJoint2D.connectedBody = element.rigidbody2d;
        fixedJoint2D.enabled       = true;
        gameObject.tag             = element.gameObject.tag;
        //rigidbody2d.Sleep();
        is_Connected = true;
        PlayerID     = playerID;
        Vector2 position = (element.transform.position + transform.position) / 2;

        //ConnectVFX.transform.position = position;
        //particleSystem.Play();


        if (type == 0)
        {
            // Player player = other.parent.GetComponent<Player>();
            // player.AddCircle(element);
        }
    }
示例#9
0
        private void OnConnect(int deviceId)
        {
            Debug.Log($"OnConnect({deviceId})");

            bool isReconnect;

            PlayerManager.Instance.ConnectPlayer(deviceId, out isReconnect);

            ConnectEvent?.Invoke(this, new ConnectEventArgs(deviceId, isReconnect));
        }
示例#10
0
 public void StartCycleMeasureCurrent()
 {
     cts = new CancellationTokenSource();
     if (!StateConnect)
     {
         Exception = null;
         cycleTask = StartCycle(cts.Token);
     }
     ConnectEvent?.Invoke(this, new EventArgs());
 }
示例#11
0
        protected virtual void OnConnect(int attackID)
        {
            //Debug.Log("Connect");
            AttackData currData = m_currAttackStruct.attackDatas[attackID];


            //currData.ID = Random.Range(-100000000, 100000000);
            //Debug.Log("ID = " + currData.ID);

            OnConnectEvent.Invoke(m_attackType, currData, 0);
        }
示例#12
0
        public void Start()
        {
            try
            {
                // Reset the variables which are set earlier
                _isConnected.Reset();
                _isSending.Reset();

                // Continue trying until there's a connection.
                bool success;

                _state = new StateObject
                {
                    Guid              = Guid.NewGuid(),
                    LastConnection    = DateTime.UtcNow,
                    ReceiveBuffer     = new byte[65536],
                    ReceiveBufferSize = 65536
                };

                do
                {
                    _state.WorkSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    _state.WorkSocket.BeginConnect(_clientSettings.EndPoint, ConnectCallback, _state);

                    success = _isConnected.WaitOne(10000);
                } while (!success);

                // We are connected!

                _isRunning      = true;
                _isShuttingDown = false;

                ConnectEvent?.Invoke();

                _state.WorkSocket.BeginReceive(_state.ReceiveBuffer, 0, _state.ReceiveBufferSize, 0, ReceiveCallback,
                                               _state);
            }
            catch (SocketException ex)
            {
                switch (ex.NativeErrorCode)
                {
                case 10054:     // An existing connection was forcibly closed by the remote host
                    Stop();
                    Start();
                    break;

                default:
                    throw;
                }
            }
        }
示例#13
0
        public void Connect()
        {
            string result = GetRequest("http://mfd.ru/export/");

            if (result == null)
            {
                ServerStatus = ServerConnectStatus.Disconnect;
            }
            else
            {
                ServerStatus = ServerConnectStatus.Connect;
                ConnectEvent?.Invoke();
            }
        }
示例#14
0
        public void Connect()
        {
            string result = GetRequest("http://iss.moex.com/iss/engines/");

            if (result == null)
            {
                ServerStatus = ServerConnectStatus.Disconnect;
            }
            else
            {
                ServerStatus = ServerConnectStatus.Connect;
                ConnectEvent?.Invoke();
            }
        }
 public void StartCycleMeasureCurrent()
 {
     //updPressure = new AutoResetEvent(false);
     //pressSystem.UpdateMeasures += (obj, e) => updPressure.Set();
     if (!StateConnect)
     {
         Exception         = null;
         cts               = new CancellationTokenSource();
         cancellationToken = cts.Token;
         cycleTask         = StartCycle(cancellationToken);
         StateConnect      = true;
     }
     ConnectEvent?.Invoke(this, new EventArgs());
 }
示例#16
0
        /// <summary>
        /// Callback method for when the net client establishes a connection with a server.
        /// </summary>
        /// <param name="loginResponse">The login response received from the server.</param>
        private void OnClientConnect(LoginResponse loginResponse)
        {
            // First relay the addon order from the login response to the addon manager
            _addonManager.UpdateNetworkedAddonOrder(loginResponse.AddonOrder);

            // We should only be able to connect during a gameplay scene,
            // which is when the player is spawned already, so we can add the username
            _playerManager.AddNameToPlayer(HeroController.instance.gameObject, _username,
                                           _playerManager.LocalPlayerTeam);

            Logger.Get().Info(this, "Client is connected, sending Hello packet");

            // If we are in a non-gameplay scene, we transmit that we are not active yet
            var currentSceneName = SceneUtil.GetCurrentSceneName();

            if (SceneUtil.IsNonGameplayScene(currentSceneName))
            {
                Logger.Get().Error(this,
                                   $"Client connected during a non-gameplay scene named {currentSceneName}, this should never happen!");
                return;
            }

            var transform = HeroController.instance.transform;
            var position  = transform.position;

            Logger.Get().Info(this, "Sending Hello packet");

            _netClient.UpdateManager.SetHelloServerData(
                _username,
                SceneUtil.GetCurrentSceneName(),
                new Vector2(position.x, position.y),
                transform.localScale.x > 0,
                (ushort)AnimationManager.GetCurrentAnimationClip()
                );

            // Since we are probably in the pause menu when we connect, set the timescale so the game
            // is running while paused
            PauseManager.SetTimeScale(1.0f);

            UiManager.InternalChatBox.AddMessage("You are connected to the server");

            try {
                ConnectEvent?.Invoke();
            } catch (Exception e) {
                Logger.Get().Warn(this,
                                  $"Exception thrown while invoking Connect event, {e.GetType()}, {e.Message}, {e.StackTrace}");
            }
        }
示例#17
0
        /// <summary>
        /// Callback method for when the client receives a login response from a server connection.
        /// </summary>
        /// <param name="loginResponse">The LoginResponse packet data.</param>
        private void OnConnect(LoginResponse loginResponse)
        {
            Logger.Get().Info(this, "Connection to server success");

            // De-register the connect failed and register the actual timeout handler if we time out
            UpdateManager.OnTimeout -= OnConnectTimedOut;
            UpdateManager.OnTimeout += () => {
                ThreadUtil.RunActionOnMainThread(() => {
                    TimeoutEvent?.Invoke();
                });
            };

            // Invoke callback if it exists on the main thread of Unity
            ThreadUtil.RunActionOnMainThread(() => {
                ConnectEvent?.Invoke(loginResponse);
            });

            IsConnected = true;
        }
示例#18
0
        public bool AssignSocket(Socket socket, Server server)
        {
            lock (SyncRoot) {
                if (socket == m_Socket)
                {
                    return(false);
                }
                if (m_Socket != null)
                {
                    DisconnectInternal(null);
                }
                m_Socket = socket;
                if (m_Socket == null)
                {
                    return(false);
                }
                m_Socket.NoDelay        = true;
                m_Socket.ReceiveTimeout = 1000;
                m_Socket.SendTimeout    = 1000;
                CreateThreads(server);

                m_LocalEndpoint  = (IPEndPoint)socket.LocalEndPoint;
                m_RemoteEndpoint = (IPEndPoint)socket.RemoteEndPoint;

                Log(LogLevel.Info, "Connected: Local={0}; Remote={1}", m_LocalEndpoint.ToString(), m_RemoteEndpoint.ToString());
            }

            try {
                OnConnect(server);
                if (ConnectEvent != null)
                {
                    ConnectEvent.Invoke(this, new ConnectEventArgs(server));
                }
                PostInit(server);
            }
            catch (Exception ex) {
                GameDebugger.NetLog(LogLevel.Error, "Exception while initializing socket: {0}", ex);
                OnInitException(server, ex);
            }

            return(true);
        }
示例#19
0
        public void Connect()
        {
            if (QuikLua == null)
            {
                QuikLua = new QuikSharp.Quik(QuikSharp.Quik.DefaultPort, new InMemoryStorage());
                QuikLua.Events.OnConnected            += EventsOnOnConnected;
                QuikLua.Events.OnDisconnected         += EventsOnOnDisconnected;
                QuikLua.Events.OnConnectedToQuik      += EventsOnOnConnectedToQuik;
                QuikLua.Events.OnDisconnectedFromQuik += EventsOnOnDisconnectedFromQuik;
                QuikLua.Events.OnTrade += EventsOnOnTrade;
                QuikLua.Events.OnOrder += EventsOnOnOrder;
                QuikLua.Events.OnQuote += EventsOnOnQuote;
                QuikLua.Events.OnFuturesClientHolding += EventsOnOnFuturesClientHolding;
                QuikLua.Events.OnFuturesLimitChange   += EventsOnOnFuturesLimitChange;

                QuikLua.Service.QuikService.Start();
                ServerStatus = ServerConnectStatus.Connect;
                ConnectEvent?.Invoke();
            }
        }
示例#20
0
 public void Connect(int outChannelNumber, CancellationToken cancellationToken)
 {
     try
     {
         ClearException();
         if (!ConnectState)
         {
             BeginConnectEvent?.Invoke(this, new EventArgs());
             commands.Connect(outChannelNumber, cancellationToken);
             taskCycleRead = StartCycleRead();
             ConnectState  = true;
         }
         ConnectEvent?.Invoke(this, new EventArgs());
     }
     catch (OperationCanceledException)
     {
         throw;
     }
     catch (Exception ex)
     {
         throw new PressSystemException(ex.Message);
     }
 }
示例#21
0
    public void OnConnectEvent(int socketID, int connectionId, NetworkError error)
    {
        //connectionsID.Add(connectionId);

        ConnectionInfo connectedNode = new ConnectionInfo
        {
            ConnectionID  = connectionId,
            connectedNode = new NodeInfo
            {
                socketID = socketID,
                port     = -1,
                nickName = "Guest" + DateTime.Now,
            }
        };

        KnowNodes.Add(connectedNode);

        ConnectEvent?.Invoke(connectedNode);

        print("|Connection event: " +
              " |HostId: " + socketID +
              " |ConnectionId : " + connectionId +
              " |Error: " + error.ToString());
    }
示例#22
0
        private void EventsOnOnConnected()
        {
            ServerStatus = ServerConnectStatus.Connect;

            ConnectEvent?.Invoke();
        }
示例#23
0
 private void EventsOnOnConnectedToQuik(int port)
 {
     ServerStatus = ServerConnectStatus.Connect;
     ConnectEvent?.Invoke();
 }
示例#24
0
 protected virtual void OnConnectEvent(ConnectEventArgs e)
 {
     ConnectEvent?.Invoke(this, e);
 }
示例#25
0
 protected void OnConnectEvent()
 {
     ServerStatus = ServerConnectStatus.Connect;
     ConnectEvent?.Invoke();
 }
示例#26
0
        public NotesView(EList <EasyRoom> notes) : base()
        {
            Width      = 780;
            AutoScroll = true;
            Notes      = notes;

            Rows = new EList <GameNoteView>();

            GameNoteView row;

            for (int i = 0; i < notes.Count; i++)
            {
                GameNoteView temp;
                if (i > 0)
                {
                    temp = new GameNoteView(notes[i])
                    {
                        Parent = this, Location = new Point(0, Rows.Last().Location.Y + 60)
                    };
                }
                else
                {
                    temp = new GameNoteView(notes[i])
                    {
                        Parent = this, Location = new Point(0, 0)
                    };
                }
                temp.ConnectEvent += (r) => {
                    ConnectEvent?.Invoke(r, notes[i]);
                };
                temp.WatchEvent += (r) => {
                    WatchEvent?.Invoke(r, notes[i]);
                };
                Rows.Add(temp);
            }

            // обновление списка лобби при добвление новых записей
            Notes.AfterAddEvent += (item) => {
                if (Rows.Count > 0)
                {
                    row = new GameNoteView()
                    {
                        Parent = this, Location = new Point(0, Rows.Last().Location.Y + 60)
                    };
                    if (row.InvokeRequired)
                    {
                        row.Invoke(new Action <EasyRoom>((s) => row.SetSource(s)), item);
                    }
                    else
                    {
                        row.SetSource(item);
                    }
                }
                else
                {
                    row = new GameNoteView()
                    {
                        Parent = this, Location = new Point(0, 0)
                    };

                    if (row.InvokeRequired)
                    {
                        row.Invoke(new Action <EasyRoom>((s) => row.SetSource(s)), item);
                    }
                    else
                    {
                        row.SetSource(item);
                    }
                }
                row.ConnectEvent += (r) => {
                    ConnectEvent?.Invoke(r, item);
                };
                row.WatchEvent += (r) => {
                    WatchEvent?.Invoke(r, item);
                };
                Rows.Add(row);
            };

            // обновляем список лобби при удалении записи (при отключении сервера / завершении игры на сервере)
            Notes.BeforeRemoveEvent += (item) => {
                row = new GameNoteView(item);
                for (int i = Rows.Count - 1; i > Rows.IndexOf(row); i--)
                {
                    if (Rows[i].Equals(row) == false)
                    {
                        Rows[i].Location = Rows[i - 1].Location;
                    }
                }
                Rows.Remove(row);
            };
        }
示例#27
0
 private void WebSocket_Opened(object sender, System.EventArgs e)
 {
     ConnectEvent?.Invoke(this, new System.EventArgs());
 }
示例#28
0
 private void OnConnect(string connectMessage)
 {
     ConnectEvent?.Invoke(this, new SubscriptionEventArgs(connectMessage));
 }
示例#29
0
 private void ClientOnConnected()
 {
     ConnectEvent?.Invoke();
     ServerStatus = ServerConnectStatus.Connect;
 }
示例#30
0
 private void OnConnectEvent()
 {
     ConnectEvent?.Invoke(this, System.EventArgs.Empty);
 }