Beispiel #1
0
        public ValueTuple <byte[], int> Compile()
        {
            using var sb = IReusableStringBuilder.Get();

            sb.Append(HttpVersion);
            sb.Append(" ");
            sb.Append(GetStatus());
            sb.Append("\r\n");
            var contentLenField = new FieldContentLength(this.ContentLength);

            foreach (var responseField in Fields)
            {
                sb.Append(responseField.Compile());
                sb.Append("\r\n");
            }
            sb.Append("Connection: close");
            sb.Append("\r\n");

            sb.Append(contentLenField.Compile());
            sb.Append("\r\n\r\n");

            var str = sb.ToString();

            this.Buffer = BytePoolShared.Rent(str !.Length);

            Encoding.UTF8.GetBytes(str, Buffer.AsSpan(0, str.Length));

            return(Buffer, str.Length);
        }
        public static byte[] Handshake(WebSocketHttpRequest request, string subProtocol)
        {
            FleckLog.Debug("Building Draft76 Response");
            // project created by an ti, given to di ma.
            using var builder = IReusableStringBuilder.Get();
            builder.StringBuilder.Append("HTTP/1.1 101 WebSocket Protocol Handshake\r\n");
            builder.StringBuilder.Append("Upgrade: WebSocket\r\n");
            builder.StringBuilder.Append("Connection: Upgrade\r\n");
            builder.StringBuilder.AppendFormat("Sec-WebSocket-Origin: {0}\r\n", request["Origin"]);
            builder.StringBuilder.AppendFormat("Sec-WebSocket-Location: {0}://{1}{2}\r\n", request.Scheme, request["Host"], request.Path);

            if (subProtocol != null)
            {
                builder.StringBuilder.AppendFormat("Sec-WebSocket-Protocol: {0}\r\n", subProtocol);
            }

            builder.Append("\r\n");

            var key1      = request["Sec-WebSocket-Key1"];
            var key2      = request["Sec-WebSocket-Key2"];
            var challenge = new ArraySegment <byte>(request.Bytes, request.Bytes.Length - 8, 8);

            var answerBytes = CalculateAnswerBytes(key1, key2, challenge);

            byte[] byteResponse       = Encoding.ASCII.GetBytes(builder.StringBuilder.ToString());
            int    byteResponseLength = byteResponse.Length;

            Array.Resize(ref byteResponse, byteResponseLength + answerBytes.Length);
            Array.Copy(answerBytes, 0, byteResponse, byteResponseLength, answerBytes.Length);

            return(byteResponse);
        }
        private static string CreateHelp(IPlayerCommand[] commands)
        {
            using var sb = IReusableStringBuilder.Get();
            foreach (var gameCommand in commands)
            {
                sb.AppendLine($"{gameCommand.Data.Prefix} -> {gameCommand.Data.Help}");
            }

            var result = sb.ToString();

            return(result);
        }
Beispiel #4
0
        public string Serialize()
        {
            using var sb = IReusableStringBuilder.Get();
            sb.AppendLine("{");
            foreach (var value in Values)
            {
                sb.AppendLine($"\"{value.Variable}\": {value.Value}{(value == Values.Last() ? "" : ",")}");
            }
            sb.AppendLine("}");
            var data = sb.ToString();

            return(data);
        }
        public static async ValueTask <string> ReadLineSizedBuffered(Stream stream, ushort length = 128)
        {
            stream.ReadTimeout = HttpConstant.ReadTimeout;
            var buffer = Pool.Rent(length);

            using var sb = IReusableStringBuilder.Get();
            var total = 0;

            try
            {
                while (total < length)
                {
                    if (!stream.CanRead)
                    {
                        return(sb.StringBuilder.Length > 0 ? sb.ToString() : null);
                    }
                    var read = await stream.ReadAsync(buffer, 0, length);

                    if (read == 0)
                    {
                        return(sb.ToString());
                    }

                    total += read;

                    if (ProcessChunks(buffer, length, read, sb))
                    {
                        return(sb.ToString());
                    }
                }

                return(sb.ToString());
            }
            catch (SocketException)
            {
                return(null);
            }
            catch (IOException)
            {
                return(null);
            }
            catch (Exception ex)
            {
                ILogManager.Log("Http read line error.", "IO.Reader", LogType.Error, toConsole: false, ex: ex);
                return(null);
            }
            finally
            {
                Pool.Return(buffer);
            }
        }
        private string GetRecords()
        {
            using var sb = IReusableStringBuilder.Get();
            sb.AppendLine($"It is {DateTime.Now}<br>");

            foreach (var instanceResult in ThreadMonitor.Results.OrderByDescending(i => i.Value))
            {
                sb.Append($"Thread ID: {instanceResult.Key} : {Indent}{instanceResult.Value}%<br>");
            }

            var result = sb.ToString();

            return(result);
        }
        private static bool ProcessChunks(byte[] buffer, int length, int read, IReusableStringBuilder sb)
        {
            Span <char> chars = stackalloc char[length];
            var         data  = buffer.AsSpan().Slice(0, read);

            if (data.Slice(read - 4).SequenceEqual(CrLfx2))
            {
                Encoding.UTF8.GetChars(data, chars);
                sb.Append(chars.Slice(0, read - 4));
                return(true);
            }
            Encoding.UTF8.GetChars(data, chars);
            sb.Append(chars.Slice(0, read));
            return(false);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="variableNames">The names of the global variables that will be updated by the receive function.</param>
        /// <param name="plots">The plot function as generated by the SpliceGraph method.</param>
        /// <param name="ctxDeclarationsNames">The names of the graph contexts, present in the HTML declarations.</param>
        /// <returns></returns>
        public static string SpliceMainScript(ushort port, string apiHandle, string[] variableNames, string[] plots, string[] ctxDeclarationsNames)
        {
            using var sb = IReusableStringBuilder.Get();

            foreach (var variable in variableNames)
            {
                sb.AppendLine($"var {variable} = null;");
            }

            var variables = sb.ToString();

            sb.Clear();

            foreach (var ctx in ctxDeclarationsNames)
            {
                sb.AppendLine($"var x{ctx} = document.getElementById('{ctx}');");
                sb.AppendLine($"var {ctx} = x{ctx}.getContext('2d');");
                sb.AppendLine("\n");
            }

            var ctxStr = sb.ToString();

            sb.Clear();

            foreach (var plot in plots)
            {
                sb.AppendLine($"\n{plot}\n");
            }

            var plotsStr = sb.ToString();

            sb.Clear();

            foreach (var receiverName in variableNames)
            {
                sb.AppendLine($"{receiverName} = receivedJson.{receiverName};");
            }

            var receiverStr = sb.ToString();

            return(GraphPageSplicerConstant.MainScriptCode
                   .Replace(GraphPageSplicerConstant.ReplaceInValue, variables)
                   .Replace(GraphPageSplicerConstant.ReplaceInCtx, ctxStr)
                   .Replace(GraphPageSplicerConstant.ReplaceInPlot, plotsStr)
                   .Replace(GraphPageSplicerConstant.ReplaceInJsonExtracts, receiverStr)
                   .Replace("%handle%", apiHandle)
                   .Replace("%port%", port.ToString()));
        }
        public string GetLatest()
        {
            lock (this._sync)
            {
                if (!this.Update)
                {
                    return(this.Content);
                }
                using var sb = IReusableStringBuilder.Get();
                sb.Append(this.StartHtml);

                foreach (var simpleElement in _elements)
                {
                    sb.Append(simpleElement.Code);
                }

                sb.Append(this.EndHtml);
                this.Content = sb.ToString();
                return(this.Content);
            }
        }
        public static string SpliceFinalHtml(string script, string title, string[] graphNames, byte width)
        {
            using var sb = IReusableStringBuilder.Get();

            foreach (var graphName in graphNames)
            {
                sb.Append("\r\n");
                sb.AppendLine("<div class=\"chart-container\">");
                sb.AppendLine($"    <canvas id=\"{graphName}\"></canvas>");
                sb.AppendLine("</div>");
                sb.AppendLine("\r\n");
            }

            var declarations = sb.ToString();

            return(GraphPageSplicerConstant.Html
                   .Replace(GraphPageSplicerConstant.ReplaceInScript, script)
                   .Replace(GraphPageSplicerConstant.ReplaceInTitle, title)
                   .Replace(GraphPageSplicerConstant.ReplaceInHtmlDeclarations, declarations)
                   .Replace(GraphPageSplicerConstant.ReplaceInWidth, width.ToString()));
        }
Beispiel #11
0
        private void Tick(object sender, ElapsedEventArgs e)
        {
            var exceptions = Exceptions.OrderByDescending(x => x.Value).ToArray();

            Exceptions.Clear();
            using var sb = IReusableStringBuilder.Get();
            sb.Append("It is ");
            sb.Append(DateTime.Now.ToString());
            if (exceptions.Length != 0)
            {
                sb.Append("<br>");
                foreach (var(key, value) in exceptions)
                {
                    sb.Append("Name: \"");
                    sb.Append(key);
                    sb.Append("\", thrown last second: ");
                    sb.Append(value.ToString());
                    sb.Append("<br>");
                }
            }

            Page.Set(sb.ToString(), Color.Transparent);
        }
 public static void Return(IReusableStringBuilder sb) => Pool.Return((ReusableStringBuilder)sb);