Last active
September 5, 2022 10:41
-
-
Save bjoerntx/f5557e87cca1ee3678d59d5d99dda88b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Http; | |
using System; | |
using System.Linq; | |
using System.Net; | |
using System.Threading.Tasks; | |
using TXTextControl.Web; | |
public class CustomWebSocketMiddleware { | |
private RequestDelegate m_next; | |
private IPAddress m_serviceAddress; | |
private int m_servicePort; | |
internal static readonly byte[] DefaultServiceAddress = { 127, 0, 0, 1 }; | |
internal const int DefaultServicePort = 4279; | |
public CustomWebSocketMiddleware(RequestDelegate next) { | |
m_next = next; | |
m_serviceAddress = new IPAddress(DefaultServiceAddress); | |
m_servicePort = DefaultServicePort; | |
} | |
public CustomWebSocketMiddleware(RequestDelegate next, | |
IPAddress serviceAddress, | |
int servicePort = DefaultServicePort) { | |
m_next = next; | |
m_serviceAddress = serviceAddress; | |
m_servicePort = servicePort; | |
} | |
public CustomWebSocketMiddleware(RequestDelegate next, | |
string hostNameOrAddress, | |
int servicePort = DefaultServicePort) { | |
m_next = next; | |
IPAddress addr = Dns.GetHostAddresses(hostNameOrAddress).FirstOrDefault(); | |
if (addr == null) throw new Exception($"Host '{hostNameOrAddress}' not found."); | |
m_serviceAddress = addr; | |
m_servicePort = servicePort; | |
} | |
public async Task Invoke(HttpContext context) { | |
if (context.WebSockets.IsWebSocketRequest && | |
context.WebSockets.WebSocketRequestedProtocols.Contains("TXTextControl.Web")) { | |
var ws = new WebSocketHandler(m_serviceAddress, m_servicePort); | |
await ws.Invoke(context); | |
} | |
else if (m_next != null) { | |
await m_next.Invoke(context); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment