Пример #1
0
        private void Adapter_OnClose(object sender, ProtocolAdapterCloseEventArgs e)
        {
            try
            {
                if (adapter != null && adapter.Channel != null && (adapter.Channel.State == ChannelState.Closed ||
                                                                   adapter.Channel.State == ChannelState.Aborted ||
                                                                   adapter.Channel.State ==
                                                                   ChannelState.ClosedReceived ||
                                                                   adapter.Channel.State == ChannelState.CloseSent))
                {
                    adapter.Dispose();
                    logger.LogDebugAsync("Web socket adapter disposed.").GetAwaiter();
                }
                else
                {
                    try
                    {
                        adapter.Channel.CloseAsync().GetAwaiter();
                        logger.LogDebugAsync("Web socket channel closed.").GetAwaiter();
                    }
                    catch { }

                    adapter.Dispose();
                    logger.LogDebugAsync("Web socket adapter disposed.").GetAwaiter();
                }
            }
            catch { }
        }
Пример #2
0
        private void Adapter_OnError(object sender, ProtocolAdapterErrorEventArgs args)
        {
            //Trace.TraceError("{0} - Protocol Adapter on channel {1} threw error {2}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), args.ChannelId, args.Error.Message);
            Console.WriteLine("{0} - Adpater exception - {1}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), args.Error.Message);

            Exception inner = args.Error.InnerException;

            while (inner != null)
            {
                Console.WriteLine("{0} - Adapter Exception Inner - {1}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), inner.Message);
                inner = inner.InnerException;
            }

            //Trace.WriteLine("------ Stack Trace -------");
            //Trace.TraceError(args.Error.StackTrace);
            //Trace.WriteLine("------ End Stack Trace -------");

            try
            {
                if (dict.ContainsKey(args.ChannelId))
                {
                    ProtocolAdapter adapter = dict[args.ChannelId];
                    dict.Remove(args.ChannelId);
                    adapter.Dispose();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0} - Exception disposing adapter Listener_OnError - {1}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), ex.Message);
                //Trace.TraceWarning("{0} - TCP Listener exception disposing adapter Listener_OnError", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"));
                //Trace.TraceError("{0} - Adapter dispose exception Listener_OnError - '{1}'", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"),ex.Message);
                //Trace.TraceError("{0} - Adapter dispose stack trace Listener_OnError - {1}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), ex.StackTrace);
            }
        }
Пример #3
0
        private void Adapter_OnClose(object sender, ProtocolAdapterCloseEventArgs e)
        {
            logger.LogInformationAsync("Adapter closing.").GetAwaiter();
            ProtocolAdapter adapter = null;

            try
            {
                if (container.ContainsKey(e.ChannelId))
                {
                    adapter = container[e.ChannelId];
                    logger.LogInformationAsync("Adapter on close channel id found adapter to dispose.").GetAwaiter();
                }
                else
                {
                    logger.LogInformationAsync("Adapter on close did not find a channel id available for the adapter.")
                    .GetAwaiter();
                }

                if (adapter != null && adapter.Channel != null && (adapter.Channel.State == ChannelState.Closed ||
                                                                   adapter.Channel.State == ChannelState.Aborted ||
                                                                   adapter.Channel.State ==
                                                                   ChannelState.ClosedReceived ||
                                                                   adapter.Channel.State == ChannelState.CloseSent))
                {
                    adapter.Dispose();
                    logger.LogInformationAsync("Adapter disposed.").GetAwaiter();
                }
                else
                {
                    try
                    {
                        logger.LogInformationAsync("Adpater trying to close channel.").GetAwaiter();
                        adapter.Channel.CloseAsync().GetAwaiter();
                        logger.LogInformationAsync("Adapter has closed the channel").GetAwaiter();
                    }
                    catch { }

                    adapter.Dispose();
                    logger.LogWarningAsync("Adapter disposed by default").GetAwaiter();
                }
            }
            catch (Exception ex)
            {
                logger.LogErrorAsync(ex, "Adapter on close fault").GetAwaiter();
            }
        }
Пример #4
0
 private void Adapter_OnClose(object sender, ProtocolAdapterCloseEventArgs e)
 {
     try
     {
         if ((adapter != null && adapter.Channel != null) && (adapter.Channel.State == ChannelState.Closed || adapter.Channel.State == ChannelState.Aborted || adapter.Channel.State == ChannelState.ClosedReceived || adapter.Channel.State == ChannelState.CloseSent))
         {
             adapter.Dispose();
         }
         else
         {
             try
             {
                 adapter.Channel.CloseAsync().GetAwaiter();
             }
             catch { }
             adapter.Dispose();
         }
     }
     catch { }
 }
Пример #5
0
        private void Adapter_OnClose(object sender, ProtocolAdapterCloseEventArgs e)
        {
            Console.WriteLine("Adapter closing");
            ProtocolAdapter adapter = null;

            try
            {
                if (container.ContainsKey(e.ChannelId))
                {
                    adapter = container[e.ChannelId];
                    Console.WriteLine("Adapter on close channel id found adapter to dispose.");
                }
                else
                {
                    Console.WriteLine("Adapter on close did not find a channel id available for the adapter.");
                }

                if ((adapter != null && adapter.Channel != null) && (adapter.Channel.State == ChannelState.Closed || adapter.Channel.State == ChannelState.Aborted || adapter.Channel.State == ChannelState.ClosedReceived || adapter.Channel.State == ChannelState.CloseSent))
                {
                    adapter.Dispose();
                    Console.WriteLine("Adapter disposed");
                }
                else
                {
                    try
                    {
                        Console.WriteLine("Adpater trying to close channel.");
                        adapter.Channel.CloseAsync().GetAwaiter();
                        Console.WriteLine("Adapter has closed the channel");
                    }
                    catch { }
                    adapter.Dispose();
                    Console.WriteLine("Adapter disposed by default");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Adapter on close fault - {ex.Message}");
            }
        }
Пример #6
0
 private async void Adapter_OnClose(object sender, ProtocolAdapterCloseEventArgs args)
 {
     try
     {
         if (dict.ContainsKey(args.ChannelId))
         {
             ProtocolAdapter adapter = dict[args.ChannelId];
             dict.Remove(args.ChannelId);
             adapter.Dispose();
         }
     }
     catch (Exception ex)
     {
         await logger.LogErrorAsync(ex, "Disposing adapter.");
     }
 }
Пример #7
0
        public async Task StopAsync()
        {
            await logger?.LogInformationAsync(
                $"UDP Listener stopping on Address {localEP.Address} and Port {localEP.Port}");

            if ((dict != null) & (dict.Count > 0))
            {
                var keys = dict.Keys;
                if (keys != null && keys.Count > 0)
                {
                    try
                    {
                        string[] keysArray = keys.ToArray();
                        foreach (var key in keysArray)
                        {
                            if (dict.ContainsKey(key))
                            {
                                ProtocolAdapter adapter = dict[key];
                                dict.Remove(key);
                                try
                                {
                                    adapter.Dispose();
                                    await logger.LogWarningAsync(
                                        $"UDP Listener stopping and dispose Protcol adapter {key}");
                                }
                                catch (Exception ex)
                                {
                                    await logger.LogErrorAsync(ex,
                                                               "Fault dispose protcol adaper while Stopping UDP Listener - {ex.Message}");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        await logger.LogErrorAsync(ex, "UDP Listener fault during stop.'");
                    }
                }
            }
            else
            {
                await logger.LogWarningAsync("No protocol adapters in TCP Listener dictionary to dispose and remove");
            }

            listener.Close();
        }
Пример #8
0
        public async Task StopAsync()
        {
            logger?.LogInformation("TCP Listener stopping on Address {0} and Port {1}", serverIP.ToString(), serverPort);
            //dispose all adapters first
            if (dict != null & dict.Count > 0)
            {
                var keys = dict.Keys;
                if (keys != null && keys.Count > 0)
                {
                    try
                    {
                        string[] keysArray = keys.ToArray();
                        foreach (var key in keysArray)
                        {
                            if (dict.ContainsKey(key))
                            {
                                ProtocolAdapter adapter = dict[key];
                                dict.Remove(key);
                                try
                                {
                                    adapter.Dispose();
                                    logger.LogWarning("TCP Listener stopping and dispose Protcol adapter {0}", key);
                                }
                                catch (Exception ex)
                                {
                                    logger.LogError("Fault dispose protcol adaper while Stopping TCP Listener - {0}", ex.Message);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.LogError("{TCP Listener fault during stop '{0}'", ex.Message);
                    }
                }
            }
            else
            {
                logger.LogWarning("No protocol adapters in TCP Listener dictionary to dispose and remove");
            }

            listener.Stop();

            await Task.CompletedTask;
        }
Пример #9
0
        private void Adapter_OnClose(object sender, ProtocolAdapterCloseEventArgs args)
        {
            //Trace.TraceWarning("{0} - Protocol adapter on channel {1} closing.", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), args.ChannelId);

            try
            {
                if (dict.ContainsKey(args.ChannelId))
                {
                    ProtocolAdapter adapter = dict[args.ChannelId];
                    dict.Remove(args.ChannelId);
                    adapter.Dispose();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0} - Exception disposing adapter Listener_OnClose - {1}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), ex.Message);
                //Trace.TraceWarning("{0} - TCP Listener exception disposing adapter Listener_OnClose", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"));
                //Trace.TraceError("{0} - Adapter dispose exception Listener_OnClose - '{1}'", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"),ex.Message);
                //Trace.TraceError("{0} - Adapter dispose stack trace Listener_OnClose - {1}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), ex.StackTrace);
            }
        }
Пример #10
0
        public async Task Invoke(HttpContext context)
        {
            source = new CancellationTokenSource();
            if (context.Request.Method.ToUpperInvariant() == "POST")
            {
                //sending a message
                adapter = ProtocolAdapterFactory.Create(config, graphManager, context, null, null, source.Token);
                adapter.Init();
            }
            else if (context.Request.Method.ToUpperInvariant() == "GET")
            {
                //long polling
                adapter            = ProtocolAdapterFactory.Create(config, graphManager, context, null, null, source.Token);
                adapter.OnObserve += Adapter_OnObserve;
                adapter.Init();
                this.context = context;
                ThreadPool.QueueUserWorkItem(new WaitCallback(Listen), waitHandles[0]);
                WaitHandle.WaitAll(waitHandles);
                adapter.Dispose();
            }

            await Task.CompletedTask;
        }
Пример #11
0
 private void Adapter_OnClose(object sender, ProtocolAdapterCloseEventArgs e)
 {
     adapter.Dispose();
 }
Пример #12
0
        /// <summary>
        /// 发送服务器列表Ping请求
        /// </summary>
        /// <param name="hostname">主机名</param>
        /// <param name="port">端口</param>
        /// <returns></returns>
        public ServerListPingResult ServerListPing(string hostname, ushort port)
        {
            if (State != MinecraftClientState.InTitle)
            {
                throw new InvalidOperationException($"invalid client state {State}, it should be {MinecraftClientState.InTitle}.");
            }
            const int timeout    = 10000;
            var       timedOut   = false;
            var       handshaked = false;

            _logger.Info($"Pinging {hostname}, {port}");
            var result = new ServerListPingResult
            {
                Delay = -1
            };
            DateTime        time1;
            TcpClient       client  = null;
            ProtocolAdapter adapter = null;

            try
            {
                client = new TcpClient();
                client.Connect(hostname, port);
                adapter = new ProtocolAdapter(client.GetStream(), PacketBoundTo.Server);
                adapter.Start();
                _ = Task.Run(async() =>  // timeout
                {
                    await Task.Delay(timeout);
                    if (adapter.State != ProtocolState.Closed)
                    {
                        timedOut = true;
                        client.Close();
                        _logger.Warn($"{hostname}:{port} timed out");
                    }
                });
                adapter.WritePacket(new HandshakePacket //handshake
                {
                    NextState       = ProtocolState.Status,
                    ProtocolVersion = _protocolVersion,
                    ServerAddress   = hostname,
                    ServerPort      = port
                });
                adapter.WritePacket(new StatusRequestPacket());
                var statusResponsePacket = (StatusResponsePacket)adapter.ReadPacket();
                handshaked = true;
                result.LoadContent(statusResponsePacket.Content);
                time1 = DateTime.Now;
                adapter.WritePacket(new StatusPingPacket {
                    Payload = time1.ToUnixTimeStamp()
                });
                if ((StatusPongPacket)adapter.ReadPacket() != null)
                {
                    result.Delay = (int)(DateTime.Now - time1).TotalMinutes;
                }
                adapter.Close();
            }
            catch
            {
                if (!handshaked)
                {
                    throw;
                }
            }
            finally
            {
                adapter?.Dispose();
                client?.Dispose();
            }
            if (timedOut)
            {
                _logger.Warn("Pinging timeout");
            }
            return(result);
        }