示例#1
0
        private void SafeInvokeDisconnected()
        {
            if (this.Disconnected == null)
            {
                return; //No Listeners
            }

            DisconnectedEvent listener = null;

            Delegate[] dels = this.Disconnected.GetInvocationList();

            foreach (Delegate del in dels)
            {
                try
                {
                    listener = (DisconnectedEvent)del;
                    listener.Invoke();
                }
                catch (Exception)
                {
                    //Could not reach the destination, so remove it
                    //from the list
                    this.Disconnected -= listener;
                }
            }
        }
示例#2
0
 void HandleDisconnectedEvent()
 {
     if (DisconnectedEvent != null)
     {
         DisconnectedEvent.Invoke();
     }
 }
示例#3
0
        /// <summary>
        /// Disconnects the session with the given reason.
        /// </summary>
        /// <param name="reason">The reason for the disconnect.</param>
        public async Task DisconnectAsync(string reason)
        {
            try {
                if (!IsConnected)
                {
                    return;
                }

                Logger.Info($"Session {Id} disconnecting: {reason}");

                if (null != _socket)
                {
                    await _socket.DisconnectAsync(false).ConfigureAwait(false);
                }
                else if (null != _sslSocket)
                {
                    await _sslSocket.DisconnectAsync(false).ConfigureAwait(false);
                }

                DisconnectedEvent?.Invoke(this, new DisconnectedEventArgs
                {
                    Reason = reason
                }
                                          );
            } catch (SocketException e) {
                Logger.Error("Error disconnecting socket!", e);
            }
        }
示例#4
0
        public void Disconnect()
        {
            if (!IsActive)
            {
                return;
            }

            if (m_Connection.ConnectionId != NetworkTransport.INVALID_CONNECTION)
            {
                byte error;
                UNET.NetworkTransport.Disconnect(m_Connection.SocketId, m_Connection.ConnectionId, out error);
                m_Connection.ConnectionId = NetworkTransport.INVALID_CONNECTION;
                m_Connection.LastError    = (NetworkError)error;
            }

            if (m_State == ConnectState.Connected)
            {
                m_State = ConnectState.Disconnected;
                m_Connection.IsConnected = false;
                m_ServerIp   = string.Empty;
                m_ServerPort = 0;

                InternalRemoveHost();

                if (DisconnectedEvent != null)
                {
                    DisconnectedEvent.Invoke();
                }
            }
            else
            {
                HandleConnectingFailed();
            }
        }
示例#5
0
    private async Task <byte[]> GetMessageAsync()
    {
        byte[] result = null;
        try
        {
            Byte[] receivedBytes = new byte[1024];

            Debug.Log("Reading from stream");
            int receivedAmount = await networkStream.ReadAsync(receivedBytes, 0, receivedBytes.Length);

            result = TrimBytes(receivedBytes, receivedAmount);
            Debug.Log($"Received data {receivedAmount}");
        }
        catch (ObjectDisposedException ex)
        {
            Debug.LogWarning("Connection lost with the server with ex:" + ex.ToString());
        }
        catch (Exception ex)
        {
            Debug.LogError("Exception : " + ex.ToString());
        }
        finally
        {
            if (!client.Connected)
            {
                disposed = true;
                Debug.Log("Connection lost :(");
                mainThreadService.SendToMainThread(() =>
                {
                    DisconnectedEvent?.Invoke();
                });
            }
        }
        return(result);
    }
        /// <summary>
        /// Start Running Receiving Process.
        /// </summary>
        public void RunReceive()
        {
            try
            {
                bool res = false;
                do
                {
                    if (m_AsyncReceive == null) //Disposed
                    {
                        break;
                    }

                    lock (m_SyncRoot)
                    {
                        res = !m_CurrentChannel.ReceiveAsync(m_AsyncReceive);
                    }

                    if (res)
                    {
                        ProceedReceiving(m_AsyncReceive);
                    }
                }while (res);
            }
            catch (Exception e)
            {
                Logger.Trace(e.ToString());
                DisconnectedEvent?.Invoke(this, EventArgs.Empty);
            }
        }
示例#7
0
 void HandleDisconnectedEvent(IConnection conn)
 {
     if (DisconnectedEvent != null)
     {
         DisconnectedEvent.Invoke(conn);
     }
 }
        /// <summary>
        /// Reading Length And Handles Data By [HandleReceived(byte[])] Without Length.
        /// </summary>
        /// <param name="e"></param>
        private void ProceedReceiving(SocketAsyncEventArgs e)
        {
            int transfered = e.BytesTransferred;

            if (e.SocketError != SocketError.Success || transfered <= 0)
            {
                DisconnectedEvent?.Invoke(this, EventArgs.Empty);
                return;
            }
            PacketReader reader = new PacketReader(m_RecvBuffer, 0);
            ushort       length = reader.ReadLEUInt16();
            ushort       offset = 2;

            //обрабатываем слипшиеся пакеты
            //var path = "d:\\dump.txt";
            while (length > 0 && offset < reader.Size)
            {
                byte[] data = new byte[length];
                Buffer.BlockCopy(m_RecvBuffer, offset, data, 0, length);
                //--- Console Hexadecimal
                //сначало надо вывести лог пакета в консоль
                StringBuilder builder = new StringBuilder();
                builder.Append("Recv: ");
                builder.Append(Utility.IntToHex(length));
                builder.Append(" ");
                for (int i = 0; i < length; i++)
                {
                    builder.AppendFormat("{0:X2} ", data[i]);
                }
                //не выводим Ping
                if (data[2] != 0x12)
                {
                    Console.ForegroundColor = ConsoleColor.DarkGray;
                    Logger.Trace(builder.ToString());
                    Console.ResetColor();
                }
#if DEBUG
                //--- File Hexadecimal
                //вывод лога пакетов в файл
                //не выводим Ping
                //if (data[2] != 0x12)
                //{
                //    var fs = new FileStream(path, FileMode.Append);
                //    var sw = new StreamWriter(fs);
                //    sw.WriteLine(builder.ToString());
                //    sw.Close();
                //    fs.Close();
                //}
#endif
                offset       += length;
                reader.Offset = offset;
                length        = reader.ReadLEUInt16(); //проверяем, есть ли еще пакет
                offset       += 2;
                //и только затем отправить на обработку
                HandleReceived(data); //отправляем на обработку данные пакета
            }
            reader.Clear();           //почистим буфер, инача считываются старые данные
            reader = null;
        }
示例#9
0
        public void Disconnected(string msg = "Error Connection.")
        {
            var login = _sessionClient.GetInfo(false).My.Login;

            //DiscordBotServer.Helpers.Loger.Log("Chat Disconected :( " + login);
            _sessionClient.Disconnect();
            DisconnectedEvent?.Invoke(this, new StringWrapperEventArgument()
            {
                Message = login
            });
        }
示例#10
0
        void InternalDisonnect(Connection conn)
        {
            byte disconnecingError;

            UNET.NetworkTransport.Disconnect(m_SocketId, conn.ConnectionId, out disconnecingError);

            conn.IsConnected = false;

            DisconnectedEvent?.Invoke(conn);

            m_Connections[conn.ConnectionId] = null;
        }
示例#11
0
        /// <summary>
        /// Reading Length And Handles Data By [HandleReceived(byte[])] Without Length.
        /// </summary>
        /// <param name="e"></param>
        private void ProceedReceiving(SocketAsyncEventArgs e)
        {
            int transfered = e.BytesTransferred;

            if (e.SocketError != SocketError.Success || transfered <= 0)
            {
                DisconnectedEvent?.Invoke(this, EventArgs.Empty);
                return;
            }
            PacketReader reader = new PacketReader(m_RecvBuffer, 0);
            short        length = reader.ReadLEInt16();
            short        offset = 2;

            //обрабатываем слипшиеся пакеты
            while (length > 0 && offset < reader.Size)
            {
                //--- Console Hexadecimal
                //TODO: в выводе в лог разделять слипшиеся пакеты
                StringBuilder builder = new StringBuilder();
                builder.Append("Recv: ");
                for (int i = 0; i < transfered; i++)
                {
                    builder.AppendFormat("{0:x2} ".ToUpper(), m_RecvBuffer[i]);
                }
                //не выводим Ping
                if (m_RecvBuffer[4] != 0x12)
                {
                    Console.ForegroundColor = ConsoleColor.DarkGray;
                    Logger.Trace(builder.ToString());
                    Console.ResetColor();
                }
                //--- Console Hexadecimal
                //#if DEBUG
                //вывод лога пакетов в файл
                //string path = "d:\\dump.txt"; //The path to the file, ensure that files exist.
                //FileStream fs = new FileStream(path, FileMode.Append);
                //StreamWriter sw = new StreamWriter(fs);
                //sw.WriteLine(builder.ToString());
                //sw.Close();
                //fs.Close();
                //#endif

                byte[] data = new byte[length];
                Buffer.BlockCopy(m_RecvBuffer, offset, data, 0, length);
                HandleReceived(data); //отправляем на обработку данные пакета
                offset       += length;
                reader.Offset = offset;
                length        = reader.ReadLEInt16(); //проверяем, есть ли еще пакет
                offset       += 2;
            }
            reader.Clear(); //почистим буфер, инача считываются старые данные
            reader = null;
        }
示例#12
0
    public void ConnectAndListen()
    {
        ServerSettingsLibrary.ServerData serverData = serverSettingsLibrary.GetCurrentServerData();

        IPAddress localAddr = IPAddress.Parse(serverData.IpAddress);

        client = new TcpClient();

        try
        {
            //Change to the ip adress of the server.
            client.Connect(localAddr, serverData.Port);
            Debug.Log("Connected to: " + client.Connected);
        }
        catch (SocketException ex)
        {
            Debug.LogError(ex.ToString());
        }
        catch (Exception ex)
        {
            Debug.LogError(ex.ToString());
        }
        finally
        {
            if (!client.Connected && retries < maxRetries)
            {
                retries++;
                ConnectAndListen();
            }
            else if (retries == maxRetries)
            {
                //Not connected cancel.
                DisconnectedEvent?.Invoke();
            }
            else
            {
                //Connected waiting for auth :)
                ConnectedEvent();
            }
        }

        if (client.Connected)
        {
            networkStream = client.GetStream();

            SentJoinMessage();

            //Start listening
            Debug.Log("Start listen thread");
            Task.Run(ListenAsync);
        }
    }
示例#13
0
        public static void HandleDisconnected(StateObject state)
        {
            // Notify that the user disconnected
            var e = new DisconnectedEventArgs();

            DisconnectedEvent.Invoke(null, e);

            // Clear the current work Socket
            currentState.workSocket = null;

            // Start listening for a new connection
            StartAccept(state);
        }
示例#14
0
        private void SwitcherDisconnected()
        {
            if (m_switcher != null)
            {
                // Remove callback:
                m_switcher.RemoveCallback(this);

                // release reference:
                m_switcher = null;
            }

            nullifyMixEffectsBlocks();
            DisconnectedEvent?.Invoke(this, new EventArgs());
        }
示例#15
0
        private void RecvThreadProc()
        {
            while (tcpClient != null)
            {
                NetworkPacket packet;
                try {
                    packet = NetworkPacket.Read(tcpClient.GetStream());
                } catch (Exception e) {
                    log.Info("Disconnected from peer: " + e.Message);
                    break;
                }
                HandlePacket(packet);
            }

            DisconnectedEvent?.Invoke(this, EventArgs.Empty);
        }
示例#16
0
        void HandleDisconnectEvent()
        {
            if (m_State == ConnectState.Connecting)
            {
                HandleConnectingFailed();
            }
            else
            {
                m_State = ConnectState.Disconnected;
                m_Connection.ConnectionId = NetworkTransport.INVALID_CONNECTION;
                m_Connection.IsConnected  = false;
                m_ServerIp   = string.Empty;
                m_ServerPort = 0;

                InternalRemoveHost();

                DisconnectedEvent?.Invoke();
            }
        }
示例#17
0
 /// <summary>
 /// Calls When We Need Send Data.
 /// </summary>
 private void M_AsyncSend_Do()
 {
     try
     {
         if (m_PacketQueue.Count > 0)
         {
             NetPacket packet   = m_PacketQueue.Dequeue();
             byte[]    compiled = packet.Compile();
             //--- Console Hexadecimal
             StringBuilder builder = new StringBuilder();
             builder.Append("Send: ");
             //                    Logger.Trace(builder.ToString());
             //                    builder.Clear();
             foreach (byte b in compiled)
             {
                 builder.AppendFormat("{0:X2} ", b);
             }
             //не выводим Pong
             if (compiled[4] != 0x13)
             {
                 Console.ForegroundColor = ConsoleColor.Gray;
                 Logger.Trace(builder.ToString());
                 Console.ResetColor();
             }
             //--- Console Hexadecimal
             //#if DEBUG
             //                    string path = "d:\\dump.txt"; //The path to the file, ensure that files exist.
             //                    FileStream fs = new FileStream(path, FileMode.Append);
             //                    StreamWriter sw = new StreamWriter(fs);
             //                    sw.WriteLine(builder.ToString());
             //                    sw.Close();
             //                    fs.Close();
             //#endif
             m_CurrentChannel.Send(compiled, compiled.Length, SocketFlags.None);
         }
     }
     catch (Exception e)
     {
         Logger.Trace(e.ToString());
         DisconnectedEvent?.Invoke(this, EventArgs.Empty);
     }
 }
        /// <summary>
        /// Calls When We Need Send Data
        /// </summary>
        private void M_AsyncSend_Do()
        {
            try
            {
                if (m_PacketQueue.Count <= 0)
                {
                    return;
                }

                var packet   = m_PacketQueue.Dequeue();
                var compiled = packet.Compile();
                m_CurrentChannel.Send(compiled, compiled.Length, SocketFlags.None); //отправляем пакет
                //--- Console Hexadecimal
                //вывод лога пакетов в консоль
                var builder = new StringBuilder();
                builder.Append("Send: ");
                //builder.Append(Utility.IntToHex(compiled.Length));
                //builder.Append(" ");
                foreach (var t in compiled)
                {
                    builder.AppendFormat("{0:X2} ", t);
                }
                //не выводим Pong
                if (compiled[4] == 0x13)
                {
                    return;
                }

                Console.ForegroundColor = ConsoleColor.Gray;
                Logger.Trace(builder.ToString());
                Console.ResetColor();
            }
            catch (Exception e)
            {
                Logger.Trace(e.ToString());
                DisconnectedEvent?.Invoke(this, EventArgs.Empty);
            }
        }
示例#19
0
        /// <summary>
        /// Polls the session socket and reads all of the available data.
        /// </summary>
        /// <param name="microSeconds">The microsecond poll timeout.</param>
        public async Task PollAndReceiveAllAsync(int microSeconds)
        {
            if (!IsConnected)
            {
                return;
            }

            using (MemoryStream stream = new MemoryStream()) {
                int count = -1;
                if (null != _socket)
                {
                    count = await _socket.PollAndReceiveAllAsync(microSeconds, stream).ConfigureAwait(false);
                }
                else if (null != _sslSocket)
                {
                    count = await _sslSocket.PollAndReceiveAllAsync(microSeconds, stream).ConfigureAwait(false);
                }

                if (count < 0)
                {
                    Logger.Warn($"Session {Id} remote disconnected!");
                    DisconnectedEvent?.Invoke(this, new DisconnectedEventArgs
                    {
                        Reason = Resources.DisconnectSocketClosed
                    }
                                              );
                    return;
                }

                if (0 == count)
                {
                    return;
                }

                byte[] data = stream.ToArray();
                await OnDataReceivedAsync(data, 0, data.Length).ConfigureAwait(false);
            }
        }
示例#20
0
        public void Notify(_BMDSwitcherEventType eventType, _BMDSwitcherVideoMode coreVideoMode)
        {
            switch (eventType)
            {
            case _BMDSwitcherEventType.bmdSwitcherEventTypeVideoModeChanged:
                VideoModeChangedEvent?.Invoke(this, new EventArgs());
                break;

            case _BMDSwitcherEventType.bmdSwitcherEventTypeMethodForDownConvertedSDChanged:
                MethodForDownConvertedSDChangedEvent?.Invoke(this, new EventArgs());
                break;

            case _BMDSwitcherEventType.bmdSwitcherEventTypeDownConvertedHDVideoModeChanged:
                DownConvertedHDVideoModeChangedEvent?.Invoke(this, new EventArgs());
                break;

            case _BMDSwitcherEventType.bmdSwitcherEventTypeMultiViewVideoModeChanged:
                MultiViewVideoModeChangedEvent?.Invoke(this, new EventArgs());
                break;

            case _BMDSwitcherEventType.bmdSwitcherEventTypePowerStatusChanged:
                PowerStatusChangedEvent?.Invoke(this, new EventArgs());
                break;

            case _BMDSwitcherEventType.bmdSwitcherEventTypeDisconnected:
                DisconnectedEvent?.Invoke(this, new EventArgs());
                break;

            case _BMDSwitcherEventType.bmdSwitcherEventType3GSDIOutputLevelChanged:
                SDI3GOutputLevelChangedEvent?.Invoke(this, new EventArgs());
                break;

            default:
                break;
            }
        }
示例#21
0
        private static async void DisconnectCheckTimer(object sender)
        {
            var deviceInformationCollection = await DeviceInformation.FindAllAsync(HidDevice.GetDeviceSelector(0x01, 0x05));

            if (_isConnected && deviceInformationCollection.Count == 0)
            {
                _deviceHandle.Dispose();
                _deviceHandle = null;

                _isConnected = false;
                DisconnectedEvent?.Invoke(null, new DisconnectedEventArgs {
                    IsConnected = false
                });
            }

            if (!_isConnected && deviceInformationCollection.Count > 0)
            {
                await ConnectToController(deviceInformationCollection);

                DisconnectedEvent?.Invoke(null, new DisconnectedEventArgs {
                    IsConnected = true
                });
            }
        }
 protected void OnDisconnectedEvent()
 {
     DisconnectedEvent?.Invoke(this, EventArgs.Empty);
 }
示例#23
0
 void HandleDisconnectedEvent()
 {
     DisconnectedEvent?.Invoke();
 }
示例#24
0
 public override void OnClientDisconnect(NetworkConnection conn)
 {
     base.OnClientDisconnect(conn);
     Debug.Log("disconnected");
     OnDisconnected.Invoke(null);
 }
示例#25
0
 public void OnDisconnected()
 {
     DisconnectedEvent?.Invoke(this);
 }
示例#26
0
        /// <summary>
        /// Calls When We Need Send Data.
        /// </summary>
        private void M_AsyncSend_Do()
        {
            try
            {
                if (m_PacketQueue.Count > 0)
                {
                    NetPacket packet   = m_PacketQueue.Dequeue();
                    byte[]    compiled = packet.Compile();
                    m_CurrentChannel.Send(compiled, compiled.Length, SocketFlags.None);

                    ////--- Console Hexadecimal
                    //StringBuilder builder = new StringBuilder();
                    //builder.Append("Send: ");
                    ////                    Logger.Trace(builder.ToString());
                    ////                    builder.Clear();
                    //foreach (byte b in compiled)
                    //    builder.AppendFormat("{0:X2} ", b);
                    ////не выводим Pong
                    //if (compiled[4] != 0x13)
                    //{
                    //    Console.ForegroundColor = ConsoleColor.Gray;
                    //    Logger.Trace(builder.ToString());
                    //    Console.ResetColor();
                    //}
                    //--- Console Hexadecimal
                    //#if DEBUG
                    //                    string path = "d:\\dump.txt"; //The path to the file, ensure that files exist.
                    //                    FileStream fs = new FileStream(path, FileMode.Append);
                    //                    StreamWriter sw = new StreamWriter(fs);
                    //                    sw.WriteLine(builder.ToString());
                    //                    sw.Close();
                    //                    fs.Close();
                    //#endif
#if DEBUG
                    //обрабатываем слипшиеся пакеты
                    ushort offset = 2;
                    ushort length = BitConverter.ToUInt16(compiled, 0); //проверяем, есть ли еще пакет
                    while (length > 0 && offset < compiled.Length)
                    {
                        byte[] data = new byte[length];
                        Buffer.BlockCopy(compiled, offset, data, 0, length);

                        //--- Console Hexadecimal
                        //вывод лога пакетов в консоль
                        /*StringBuilder*/
                        StringBuilder builder = new StringBuilder();
                        builder.Append("Send: ");
                        builder.Append(Utility.IntToHex(length));
                        builder.Append(" ");
                        for (int i = 0; i < length; i++)
                        {
                            builder.AppendFormat("{0:X2} ", data[i]);
                        }
                        //не выводим Ping
                        if (data[2] != 0x13)
                        {
                            Console.ForegroundColor = ConsoleColor.Gray;
                            Logger.Trace(builder.ToString());
                            Console.ResetColor();
                        }
                        //--- Console Hexadecimal
                        //#if DEBUG
                        //--- File Hexadecimal
                        //вывод лога пакетов в файл
                        //string path = "d:\\dump.txt"; //The path to the file, ensure that files exist.
                        //FileStream fs = new FileStream(path, FileMode.Append);
                        //StreamWriter sw = new StreamWriter(fs);
                        //sw.WriteLine(builder.ToString());
                        //sw.Close();
                        //fs.Close();
                        //--- File Hexadecimal

                        //                        m_CurrentChannel.Send(data, data.Length, SocketFlags.None); //отправляем на обработку данные пакета
                        offset += length;
                        if (offset >= compiled.Length)
                        {
                            break;
                        }
                        length  = BitConverter.ToUInt16(compiled, offset); //проверяем, есть ли еще пакет
                        offset += 2;
                    }
#endif
                }
            }
            catch (Exception e)
            {
                Logger.Trace(e.ToString());
                DisconnectedEvent?.Invoke(this, EventArgs.Empty);
            }
        }
示例#27
0
 private void OnDisconnected()
 {
     ClientState = ClientState.Disconnected;
     DisconnectedEvent?.Invoke();
 }
        private async Task Reader()
        {
            using (HttpClient client = new HttpClient {
                Timeout = Timeout.InfiniteTimeSpan
            })
            {
                for (int i = 1; AutoReconnect && (RetryLimit == -1 || i <= RetryLimit); i++)
                {
                    try
                    {
                        using (var response = await client.GetAsync($"https://stream.lobi.co/2/group/{GroupID}?token={AccessToken}", HttpCompletionOption.ResponseHeadersRead))
                            using (var reader = new System.IO.StreamReader(await response.Content.ReadAsStreamAsync()))
                            {
                                i         = 0;    //カウンタ初期化
                                Connected = true; //Connected!!
                                ConnectedEvent?.Invoke(GroupID);
                                while (!reader.EndOfStream)
                                {
                                    token = new CancellationTokenSource();       //トークン初期化
                                    var jobj = await _Read(reader, token.Token); //Jsonデータ読み取り

                                    var ev = jobj["event"]?.ToString();
                                    if (ev == "chat")
                                    {
                                        ChatEvent?.Invoke(GroupID, JsonConvert.DeserializeObject <Chat>(jobj["chat"].ToString()));
                                    }
                                    else if (ev == "chat_deleted")
                                    {
                                        ChatDeletedEvent?.Invoke(GroupID, jobj["id"].ToString());
                                    }
                                    else if (ev == "part")
                                    {
                                        PartEvent?.Invoke(GroupID, JsonConvert.DeserializeObject <UserMinimal>(jobj["user"].ToString()));
                                    }
                                    else if (ev == "archive")
                                    {
                                        ArchiveEvent?.Invoke(GroupID);
                                    }
                                }
                            }
                        token     = null;
                        Connected = false;
                        DisconnectedEvent?.Invoke(GroupID);
                    }
                    catch (OperationCanceledException)
                    {
                        token     = null;
                        Connected = false;
                        DisconnectedEvent?.Invoke(GroupID);
                        return;
                    }
                    catch (Exception ex)
                    {
                        if (Connected)
                        {
                            token     = null;
                            Connected = false;
                            DisconnectedEvent?.Invoke(GroupID);//必要かな??
                        }
                        else
                        {
                            token     = null;
                            Connected = false;//一応ね
                        }
                        FailConnectEvent?.Invoke(GroupID, ex);
                    }
                    await Task.Delay(RetryCoolTimeMilliseconds);//クールタイム
                }
            }
        }
示例#29
0
 public void GetDisconected(string login)
 {
     DisconnectedEvent?.Invoke(login);
 }
示例#30
0
 void HandleDisconnectedEvent(IConnection conn)
 {
     DisconnectedEvent?.Invoke(conn);
 }