Added Server Sent Events

This commit is contained in:
Michael Nolan
2022-09-01 00:26:26 -05:00
parent 3162360069
commit 9277fda0d5
4 changed files with 440 additions and 20 deletions
+91 -2
View File
@@ -78,8 +78,97 @@ namespace Tesses.WebServer
return str;
}
public static void SendNonSeekableStream(this ServerContext ctx,Stream strm,long readFor=-1,string contentType = "application/octet-stream")
{
try
{
long tread=0;
byte[] buffer=new byte[8*1024*1024];
int read=0;
do
{
if(readFor > -1){
read=(int)Math.Min(buffer.Length,readFor-tread);
}else{
read=buffer.Length;
}
if(read == 0) break;
read = strm.Read(buffer,0,read);
strm.Write(buffer,0,read);
}while(read > 0);
} finally {
strm.Close();
ctx.NetworkStream.Close();
}
}
public static async Task SendNonSeekableStreamAsync(this ServerContext ctx,Stream strm,long readFor=-1,string contentType="application/octet-stream")
{
try
{
long tread=0;
byte[] buffer=new byte[8*1024*1024];
int read=0;
do
{
if(readFor > -1){
read=(int)Math.Min(buffer.Length,readFor-tread);
}else{
read=buffer.Length;
}
if(read == 0) break;
read = await strm.ReadAsync(buffer,0,read);
await strm.WriteAsync(buffer,0,read);
}while(read > 0);
} finally {
strm.Close();
ctx.NetworkStream.Close();
}
}
public static void SendStream(this ServerContext ctx,Stream strm,string contentType="application/octet-stream")
{
//ctx.StatusCode = 200;
int start = 0, end = (int)strm.Length - 1;
if (ctx.RequestHeaders.ContainsKey(BYTES_RANGE_HEADER) && strm.CanSeek)
{
if (ctx.RequestHeaders[BYTES_RANGE_HEADER].Count > 1)
{
throw new NotSupportedException("Multiple 'Range' headers are not supported.");
}
var range = ctx.RequestHeaders[BYTES_RANGE_HEADER][0].Replace("bytes=", String.Empty)
.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => Int32.Parse(x))
.ToArray();
start = (range.Length > 0) ? range[0] : 0;
end = (range.Length > 1) ? range[1] : (int)(strm.Length - 1);
var hdrs = ctx.ResponseHeaders;
hdrs.Add("Accept-Ranges", "bytes");
hdrs.Add("Content-Range", "bytes " + start + "-" + end + "/" + strm.Length);
ctx.StatusCode = 206;
}
ctx.ResponseHeaders.Add("Content-Length", (end - start + 1).ToString());
ctx.ResponseHeaders.Add("Content-Type", contentType);
ctx.WriteHeaders();
if (!ctx.Method.Equals("HEAD", StringComparison.Ordinal))
{
try
{
if(strm.CanSeek)
strm.Position = start;
strm.CopyTo(ctx.NetworkStream, Math.Min(8 * 1024 * 1024, end - start + 1));
}
finally
{
strm.Close();
ctx.NetworkStream.Close();
}
}
}
public static async Task SendStreamAsync(this ServerContext ctx, Stream strm, string contentType = "application/octet-stream")
{
//ctx.StatusCode = 200;
@@ -116,7 +205,7 @@ namespace Tesses.WebServer
{
if(strm.CanSeek)
strm.Position = start;
strm.CopyTo(ctx.NetworkStream, Math.Min(8 * 1024 * 1024, end - start + 1));
await strm.CopyToAsync(ctx.NetworkStream, Math.Min(8 * 1024 * 1024, end - start + 1));
}
finally
{