When deploying the Angular document editor, it must be connected to a backend hosted in ASP.NET or ASP.NET Core. This backend hosts the WebSocketHandler to communicate with the client-side script to sychronize the document rendering process.

This article explains how to create an ASP.NET Core backend to host the WebSocketHandler. In this case, the TCP Service (illustrated in purple in the animation below) is hosted on the same server like the backend application.

Separated TCP Service

But in several scenarios, it might be helpful to host the TCP service separately from the ASP.NET Core backend.

Custom WebSocketMiddleware

In Step 5 of the above mentioned tutorial, the Text Control WebSocketMiddleware is added to the Startup.cs. This middleware will be replaced with the below custom middleware:

public class CustomWebSocketMiddleware
{
private RequestDelegate m_next;
private IPAddress m_serviceAddress;
private int m_servicePort;
internal static readonly byte[] DefaultServiceAddress = { 127, 0, 0, 1 };
public CustomWebSocketMiddleware(RequestDelegate next)
{
m_next = next;
m_serviceAddress = new IPAddress(DefaultServiceAddress);
m_servicePort = 4277;
}
public CustomWebSocketMiddleware(RequestDelegate next,
IPAddress serviceAddress,
int servicePort = 4277)
{
m_next = next;
m_serviceAddress = serviceAddress;
m_servicePort = servicePort;
}
public CustomWebSocketMiddleware(RequestDelegate next,
string hostNameOrAddress,
int servicePort = 4277)
{
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);
}
}
}
view raw custom.cs hosted with ❤ by GitHub

This middleware allows you to define the IP and port number of the TCP service in the constructor (from Startup.cs):

app.UseMiddleware<TXTextControl.Web.CustomWebSocketMiddleware>("127.0.0.1",4277);
view raw startup.cs hosted with ❤ by GitHub

The custom middleware calls the WebSocketHandler constructor with the given IP and port values to connect the backend with the separated TCP service.