Ejemplo n.º 1
0
        public static void SendAndCloseResponse(HttpListenerContext ctx, string text, bool throwIfError, string contentType)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            var response = ctx.Response;

            try
            {
                if (string.IsNullOrEmpty(text))
                {
                    return;
                }

                if (string.IsNullOrEmpty(contentType))
                {
                    response.ContentType = "text/xml; charset=utf-8";
                }
                else
                {
                    response.ContentType = contentType;
                }
                var buffer = Encoding.UTF8.GetBytes(text);

                if (CompressResponse)
                {
                    if (Array.Exists <string>(ctx.Request.Headers.GetValues("Accept-Encoding"), v => v == "gzip"))
                    {
                        response.AddHeader("Content-Encoding", "gzip");
                        var ms   = new MemoryStream();
                        var gzip = new GZipStream(ms, CompressionMode.Compress);
                        gzip.Write(buffer, 0, buffer.Length);
                        gzip.Close();
                        buffer = ms.ToArray();
                    }
                }

                response.ContentLength64 = buffer.Length;
                response.Headers.Add(HttpResponseHeader.CacheControl, "no-cache");
                response.Headers.Add(HttpResponseHeader.Vary, "*");
                response.Headers.Add(HttpResponseHeader.Pragma, "no-cache");
                response.OutputStream.Write(buffer, 0, buffer.Length);
                response.OutputStream.Flush();

                NetStatistics.WriteBytes(buffer.Length);
            }
            catch
            {
                if (throwIfError)
                {
                    throw;
                }
            }
            finally
            {
                try { response.Close(); }
                catch { }
            }
        }
Ejemplo n.º 2
0
 private void BeginReadCallback(IAsyncResult asyncResult)
 {
     try
     {
         var stream = (Stream)asyncResult.AsyncState;
         int readed = stream.EndRead(asyncResult);
         if (0 < readed)
         {
             streamParser.Push(buffer, 0, readed);
             BeginReceive();
             NetStatistics.ReadBytes(readed);
             packetSize += readed;
             if (packetSize > _maxPacket)
             {
                 throw new ArgumentException("request-too-large");
             }
         }
         else
         {
             Close();
         }
     }
     catch (Exception e)
     {
         LogErrorAndCloseConnection(e, "BeginReadCallback");
     }
 }
Ejemplo n.º 3
0
        public void Draw()
        {
            base.OnUpdate();
            if (timer <= 0)
            {
                timer = 0.1f;
            }
            else
            {
                timer -= Time.DeltaTime;
            }
            curFpsBuilder.Clear().Append("FPS: ").Append(fpsCounter.CurrentFPS);
            avgFpsBuilder.Clear().Append("AVG: ").Append(fpsCounter.AverageFPS);

            spriteBatch.DrawString(Console.DebugFont, curFpsBuilder, new Microsoft.Xna.Framework.Vector2(10, 10), Color.Red, 0f, Microsoft.Xna.Framework.Vector2.Zero, 1.0f, SpriteEffects.None, 1f);
            spriteBatch.DrawString(Console.DebugFont, avgFpsBuilder, new Microsoft.Xna.Framework.Vector2(160, 10), Color.Red, 0f, Microsoft.Xna.Framework.Vector2.Zero, 1.0f, SpriteEffects.None, 1f);

            NetStatistics stats = Network.Statistics;

            networkBuilder.Clear().Append("NETWORK STATISTICS\n");
            if (stats == null)
            {
                networkBuilder.Append("No connection.");
            }
            else
            {
                sec -= Time.DeltaTime;
                if (sec <= 0)
                {
                    bytesDownStart   = stats.BytesReceived;
                    bytesDownLastSec = bytesDownThisSec;
                    bytesUpStart     = stats.BytesSent;
                    bytesUpLastSec   = bytesUpThisSec;
                    sec = 1.0f;
                }
                bytesDownThisSec = stats.BytesReceived - bytesDownStart;
                bytesUpThisSec   = stats.BytesSent - bytesUpStart;
                networkBuilder.Append("PACKETS:\n")
                .Append("  Sent: ").Append(stats.PacketsSent).Append("\n")
                .Append("  Recieved: ").Append(stats.PacketsReceived).Append("\n")
                .Append("BYTES:\n")
                .Append("  Sent: ").Append(stats.BytesSent).Append(" (").Append(bytesUpLastSec / 1000).Append("KB/s) \n")
                .Append("  Recieved: ").Append(stats.BytesReceived).Append(" (").Append(bytesDownLastSec / 1000).Append("KB/s) \n")
                .Append("RTT: ").Append(Network.AverageRTT).Append("\n")
                .Append("IP: ").Append(Network.CurrentIPAddress);
            }
            spriteBatch.DrawString(Console.DebugFont, networkBuilder, new Microsoft.Xna.Framework.Vector2(10, 100), Color.Red, 0f, Microsoft.Xna.Framework.Vector2.Zero, 1.0f, SpriteEffects.None, 1f);
        }
Ejemplo n.º 4
0
        public static Body ReadBodyFromRequest(HttpListenerContext ctx)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }

            try
            {
                if (!ctx.Request.HasEntityBody)
                {
                    return(null);
                }

                byte[] data   = new byte[ctx.Request.ContentLength64];
                int    offset = 0;
                int    count  = data.Length;
                // Read may return anything from 0 to ContentLength64.
                while (0 < count)
                {
                    int readed = ctx.Request.InputStream.Read(data, offset, count);
                    if (readed == 0)
                    {
                        break;
                    }
                    offset += readed;
                    count  -= readed;
                }
                NetStatistics.ReadBytes(count);
                return(ElementSerializer.DeSerializeElement <Body>(Encoding.UTF8.GetString(data)));
            }
            catch (Exception e)
            {
                if (e is HttpListenerException || e is ObjectDisposedException)
                {
                    // ignore
                }
                else
                {
                    log.ErrorFormat("Error read body from request: {0}", e);
                }
            }
            return(null);
        }
Ejemplo n.º 5
0
        public override void Update(double totalTime, double frameTime)
        {
            base.Update(totalTime, frameTime);

            if (Time.Ticks > _time_to_update)
            {
                _time_to_update = Time.Ticks + 100;

                if (!NetClient.Socket.IsConnected)
                {
                    _ping = NetClient.LoginSocket.Statistics.Ping;
                    _deltaBytesReceived = NetClient.LoginSocket.Statistics.DeltaBytesReceived;
                    _deltaBytesSent     = NetClient.LoginSocket.Statistics.DeltaBytesSent;
                }
                else if (!NetClient.Socket.IsDisposed)
                {
                    _ping = NetClient.Socket.Statistics.Ping;
                    _deltaBytesReceived = NetClient.Socket.Statistics.DeltaBytesReceived;
                    _deltaBytesSent     = NetClient.Socket.Statistics.DeltaBytesSent;
                }

                Span <char>        span = stackalloc char[128];
                ValueStringBuilder sb   = new ValueStringBuilder(span);

                if (IsMinimized)
                {
                    sb.Append($"Ping: {_ping} ms");
                }
                else
                {
                    sb.Append($"Ping: {_ping} ms\n{"In:"} {NetStatistics.GetSizeAdaptive(_deltaBytesReceived),-6} {"Out:"} {NetStatistics.GetSizeAdaptive(_deltaBytesSent),-6}");
                }

                _cacheText = sb.ToString();

                sb.Dispose();

                Vector2 size = Fonts.Bold.MeasureString(_cacheText);

                _trans.Width   = Width = (int)(size.X + 20);
                _trans.Height  = Height = (int)(size.Y + 20);
                WantUpdateSize = true;
            }
        }
Ejemplo n.º 6
0
        public override void Update(double totalTime, double frameTime)
        {
            base.Update(totalTime, frameTime);

            if (Time.Ticks > _time_to_update)
            {
                _sb.Clear();

                _time_to_update = Time.Ticks + 100;

                if (!NetClient.Socket.IsConnected)
                {
                    _ping = NetClient.LoginSocket.Statistics.Ping;
                    _deltaBytesReceived = NetClient.LoginSocket.Statistics.DeltaBytesReceived;
                    _deltaBytesSent     = NetClient.LoginSocket.Statistics.DeltaBytesSent;
                }
                else if (!NetClient.Socket.IsDisposed)
                {
                    _ping = NetClient.Socket.Statistics.Ping;
                    _deltaBytesReceived = NetClient.Socket.Statistics.DeltaBytesReceived;
                    _deltaBytesSent     = NetClient.Socket.Statistics.DeltaBytesSent;
                }

                if (IsMinimized)
                {
                    _sb.Append($"Ping: {_ping} ms");
                }
                else
                {
                    _sb.Append
                    (
                        $"Ping: {_ping} ms\n{"In:"} {NetStatistics.GetSizeAdaptive(_deltaBytesReceived),-6} {"Out:"} {NetStatistics.GetSizeAdaptive(_deltaBytesSent),-6}"
                    );
                }


                Vector2 size = Fonts.Bold.MeasureString(_sb.ToString());

                _trans.Width   = Width = (int)(size.X + 20);
                _trans.Height  = Height = (int)(size.Y + 20);
                WantUpdateSize = true;
            }
        }
Ejemplo n.º 7
0
        public void Stop()
        {
            lock (syncRoot)
            {
                foreach (var listener in listeners.Values)
                {
                    try
                    {
                        listener.Stop();
                        log.DebugFormat("Stopped listener '{0}'", listener.Name);
                    }
                    catch (Exception e)
                    {
                        log.ErrorFormat("Error stop listener '{0}': {1}", listener.Name, e);
                    }
                }
                started = false;
            }

            log.DebugFormat("Net statistics: read bytes {0}, write bytes {1}", NetStatistics.GetReadBytes(), NetStatistics.GetWriteBytes());
        }
 private void Send(Stream stream)
 {
     if (Interlocked.CompareExchange(ref sending, 1, 0) == 0)
     {
         Tuple <byte[], Node> item;
         try
         {
             if (sendingQueue.TryDequeue(out item))
             {
                 NetStatistics.WriteBytes(item.Item1.Length);
                 stream.BeginWrite(item.Item1, 0, item.Item1.Length, WriteCallback, stream);
             }
             else
             {
                 Volatile.Write(ref sending, 0);
             }
         }
         catch (Exception e)
         {
             Volatile.Write(ref sending, 0);
             LogErrorAndCloseConnection(e, "Send");
         }
     }
 }
Ejemplo n.º 9
0
 private void Send(byte[] buffer, Node node)
 {
     NetStatistics.WriteBytes(buffer.Length);
     sendStream.BeginWrite(buffer, 0, buffer.Length, BeginWriteCallback, new object[] { sendStream, node });
 }
Ejemplo n.º 10
0
 public LiteNetStatistics(NetStatistics liteStat)
 {
     _liteStat = liteStat;
 }