Created
September 10, 2016 02:24
-
-
Save anuraj/27c63afe65dc34206cffdf2e2d1c6083 to your computer and use it in GitHub Desktop.
WebSocket middleware example
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> | |
<title>Bootstrap 101 Template</title> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> | |
<script> | |
var webSocket; | |
$().ready(function () { | |
webSocket = new WebSocket("ws://localhost:5000"); | |
webSocket.onopen = function () { | |
$("#spanStatus").text("connected"); | |
}; | |
webSocket.onmessage = function (evt) { | |
$("#spanStatus").text(evt.data); | |
}; | |
webSocket.onerror = function (evt) { | |
alert(evt.message); | |
}; | |
webSocket.onclose = function () { | |
$("#spanStatus").text("disconnected"); | |
}; | |
$("#btnSend").click(function () { | |
if (webSocket.readyState == WebSocket.OPEN) { | |
webSocket.send($("#textInput").val()); | |
} | |
else { | |
$("#spanStatus").text("Connection is closed"); | |
} | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<label>Enter Message</label><input type="text" id="textInput" /><button id="btnSend">Send</button> | |
<span id="spanStatus"></span> | |
</body> | |
</html> |
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 System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Logging; | |
using WebApp2.Middlewares; | |
namespace WebApp2 | |
{ | |
public class Startup | |
{ | |
// This method gets called by the runtime. Use this method to add services to the container. | |
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
} | |
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | |
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) | |
{ | |
loggerFactory.AddConsole(); | |
if (env.IsDevelopment()) | |
{ | |
app.UseDeveloperExceptionPage(); | |
} | |
app.UseStaticFiles(); | |
app.UseWebSockets(); | |
app.UseWebSocketHandler(); | |
app.Run(async (context) => | |
{ | |
await context.Response.WriteAsync("Hello World!"); | |
}); | |
} | |
} | |
} |
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 System; | |
using System.Net.WebSockets; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.Extensions.Logging; | |
namespace WebApp2.Middlewares | |
{ | |
public class WebSocketMiddleware | |
{ | |
private readonly RequestDelegate _next; | |
private readonly ILogger _logger; | |
public WebSocketMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) | |
{ | |
_next = next; | |
_logger = loggerFactory.CreateLogger<WebSocketMiddleware>(); | |
} | |
public async Task Invoke(HttpContext httpContext) | |
{ | |
_logger.LogInformation("Handling request: " + httpContext.Request.Path); | |
if (httpContext.WebSockets.IsWebSocketRequest) | |
{ | |
var webSocket = await httpContext.WebSockets.AcceptWebSocketAsync(); | |
while (webSocket.State == WebSocketState.Open) | |
{ | |
var token = CancellationToken.None; | |
var buffer = new ArraySegment<Byte>(new Byte[4096]); | |
var received = await webSocket.ReceiveAsync(buffer, token); | |
switch (received.MessageType) | |
{ | |
case WebSocketMessageType.Text: | |
var request = Encoding.UTF8.GetString(buffer.Array, | |
buffer.Offset, | |
buffer.Count); | |
var type = WebSocketMessageType.Text; | |
var data = Encoding.UTF8.GetBytes("Echo from server :" + request); | |
buffer = new ArraySegment<Byte>(data); | |
await webSocket.SendAsync(buffer, type, true, token); | |
break; | |
} | |
} | |
} | |
else | |
{ | |
await _next.Invoke(httpContext); | |
} | |
_logger.LogInformation("Finished handling request."); | |
} | |
} | |
public static class RequestLoggerExtensions | |
{ | |
public static IApplicationBuilder UseWebSocketHandler(this IApplicationBuilder builder) | |
{ | |
return builder.UseMiddleware<WebSocketMiddleware>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment