This project is demonstrating bidirectional connection and data transfer from low level layer (secure zone) to Browsering - DMZ (Public) zone via .NET Core WebSockets.
You can use it on your API - Service side to communicate among your trusted Backend API consumer Clients (for example MVC Web Application Hosting) and at the same time may client to be a Browser (User-Agent) then you can manage your connection and domain data transfer operation with same interface.
// Add NetCoreStack Native Socket Services.
services.AddNativeWebSockets(options => {
options.RegisterInvocator<ServerWebSocketCommandInvocator>(WebSocketCommands.All);
}); app.UseNativeWebSockets();public MyController(IConnectionManager connectionManager)
{
_connectionManager = connectionManager;
}
[HttpPost(nameof(SendAsync))]
public async Task<IActionResult> SendAsync([FromBody]SimpleModel model)
{
var echo = $"Echo from server '{model.Message}' - {DateTime.Now}";
var obj = new { message = echo };
var webSocketContext = new WebSocketMessageContext { Command = WebSocketCommands.DataSend, Value = obj };
await _connectionManager.BroadcastAsync(webSocketContext);
return Ok();
}// Client WebSocket - DMZ to API side connections
services.AddProxyWebSockets(options => {
options.WebSocketHostAddress = "localhost:7803";
options.RegisterInvocator<CustomWebSocketCommandInvocator>(WebSocketCommands.All);
});
// WebSockets for Browsers - User Agent ( javascript clients )
services.AddNativeWebSockets(options => {
options.RegisterInvocator<AgentsWebSocketCommandInvocator>(WebSocketCommands.All);
});
// Add MVC framework services.
services.AddMvc();// Proxy (Domain App) Client WebSocket - DMZ to API side connections
app.UseProxyWebSockets();
// User Agent WebSockets for Browsers
app.UseNativeWebSockets();
// Use MVC
app.UseMvc();public class CustomWebSocketCommandInvocator : IClientWebSocketCommandInvocator
{
private readonly IConnectionManager _connectionManager;
public CustomWebSocketCommandInvocator(IConnectionManager connectionManager)
{
_connectionManager = connectionManager;
}
public Task InvokeAsync(WebSocketMessageContext context)
{
// Sending incoming data from Backend zone to the Clients (Browsers)
_connectionManager.BroadcastAsync(context);
return Task.CompletedTask;
}
}dotnet restore