generated from deepgram-starters/project-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServerApp.cs
97 lines (87 loc) · 3.25 KB
/
ServerApp.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Http;
using System.Net.WebSockets;
using WebApp.Handlers;
using DotNetEnv;
using Deepgram;
using Microsoft.Extensions.Primitives;
namespace WebApp
{
public class ServerApp
{
private readonly int port;
public ServerApp(int port)
{
this.port = port;
}
public void Start()
{
// Initialize Library with default logging
// Normal logging is "Info" level
Library.Initialize();
// OR very chatty logging
// Library.Initialize(Deepgram.Logger.LogLevel.Verbose); // LogLevel.Default, LogLevel.Debug, LogLevel.Verbose
var host = new WebHostBuilder()
.UseKestrel()
.ConfigureServices(services => services.AddSingleton(this))
.Configure(app =>
{
app.UseWebSockets(); // Ensure WebSockets are enabled
var webSocketOptions = new WebSocketOptions()
{
KeepAliveInterval = TimeSpan.MaxValue,
};
app.UseWebSockets(webSocketOptions);
// handle websocket requests
app.Use(async (context, next) =>
{
Console.WriteLine($"----------- {context.Request.Path}");
if (context.Request.Path == "/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
// get the form data
var qs = context.Request.Query;
string model = qs.TryGetValue("model", out StringValues modelValues) ? modelValues.ToString() : string.Empty;
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
await new ApiHandler(webSocket, model).HandleApiRequest(context);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
// all other requests
app.Run(new RequestHandler().HandleRequest);
})
.UseUrls($"http://localhost:{port}/")
.Build();
host.Run();
}
}
public class Program
{
public static void Main(string[] args)
{
DotNetEnv.Env.Load();
string portString = Environment.GetEnvironmentVariable("port");
if (portString == null)
{
portString = "3000";
}
int.TryParse(portString, out int port);
ServerApp server = new ServerApp(port);
server.Start();
Console.WriteLine($"Server started on port {port}");
}
}
}